Learn Spring In Spring (2)

xiaoxiao2021-03-06  17

Submitter:

Bromon Time: Tuesday, 2005/03/22 - 15:04

Second, simple example of Spring management object

Bromon original, please respect the copyright

Any object that needs to be handed over to Spring must be registered in the configuration file. This process is called Wiring. Here is the simplest Hello World demo. We will register as follows:

/ ** Create a date 2005-3-22 * / package org.bromon.spring.test; / *** @Author bromon * / public class hellotalker {public string greeting () {return "hello world";}}

Then we will write a Spring profile, file name, in me, it is springconfig.xml, you need to pay attention to this file should be stored in the path contained in ClassPath:

This program is completed, because only one object HelloTalker is registered in Spring, so there is no dependence between the objects, of course, does not involve relying on relying. The following demonstrates a simple dependency injection:

The first step is to modify HelloTalker, add a string name property: public string name; write a SET method for this property, the method must strictly abide by JavaBean naming rules:

Public void setname (String name) {this.name = name;}

Modify the Greeting method:

Public string greeting () {return "hello" name;}

As you can see, the Name property has no initial test because its value will be subjected to Spring Dynamic Injection.

Step 2, modify this bean configuration in SpringConfig.xml:

bromon

Modify completion. We write a name "bromon" in SpringConfig.xml, which will be dynamically injected into the name property of Hellotalker, and the Greeting method will print it out. Re-run the JUnit class just now, you can see the result.

We only demonstrate how to inject a simplest string. In fact, we can inject any value type, or inject any class of instances, or injecting List, Map, Properties. The configuration file manages all the relationships between objects and objects, and the object is only responsible for performing its own function. The fewer responsibilities, the lower the degree of the, the easier test, the management maintenance is more easier.

There are still many attributes that are used to specify how objects are instantiated. It also has a lot of child tags for configuring the properties of the object, please refer to the relevant DTD and documentation, you can master it quickly. This series is not a Spring manual. Spring is basically referred to Spring in action, enough and accurate enough. More detailed details and advanced features of the following chapters.

转载请注明原文地址:https://www.9cbs.com/read-41796.html

New Post(0)