Spring's bean configuration

Source: Internet
Author: User
Tags instance method

IOC is actually from the opposite of our usual new object, we usually use the object is generally directly using the keyword class new object, it is obvious that the use of new so that the current module has unwittingly and new out of the object coupling, And we are usually a higher level of the abstract module calls the underlying implementation module, so that the production module depends on the implementation of concrete, which is in our Java advocated in the interface oriented abstract programming is the conflict, and this also brings the system module architecture problems. Very simple example, in the database operation, always call the DAO layer of the Business layer, DAO generally uses interface development, which to some extent satisfies the loose coupling, so that the business logic layer does not rely on the specific DAO. But when we use it, we will be new to a particular database of DAO, which is virtually binding to a particular database, although we can use the abstract factory pattern to get the DAO implementation class, but unless we write all the DAO in the database at once, Otherwise we will have to modify the DAO factory class when we are migrating the database.

So what can we achieve with IOC? IOC, the implementation of the DAO interface is no longer called the business logic layer to fetch the factory class, but through the container (such as spring) to set the DAO implementation class for our business layer. So the whole process in turn, formerly our business layer to take the initiative to obtain DAO, and now is the DAO is actively set to the business logic layer, which is the origin of inversion control. With IOC, we can seamlessly implement a database migration without modifying any code, but it is also necessary to write a DAO that implements a particular database. We put DAO generally to more cases, then the IOC will bring us more convenience, such as an interface of multiple implementations, we only need to configure the OK, and do not need to write a factory to get it. This is the loose coupling of the modules that the IOC brings to us and the ease of application.
So why is the IOC simple? In fact, it is by our usual new turn to use reflection to get the instance of the class, it is believed that anyone will use the Java reflection mechanism, it is not impossible to write an IOC framework. Like what:
......
Public Object getinstance (String className) throws Exception
{
Object obj = Class.forName (className). newinstance ();
Method[] methods = Obj.getclass (). GetMethods ();
for (Method method:methods) {
if (Method.getname (). Intern () = = "SetString") {
Method.invoke (obj, "Hello world!");
}
}
}
......

One of the methods above is to simply use the SetString method that reflects the specified class to set a Hello world! string. You can actually see the IOC is really simple, of course, the IOC simply does not mean the spring IOC is simple, the spring IOC is powerful in a series of very powerful configuration file maintenance classes, they can maintain the spring configuration file of the relationship between the various classes, This is where the IOC of spring is really powerful. In spring's bean definition file, you can not only set properties for the definition bean, but also support inheritance between beans, bean abstraction, and different fetching methods.
In the spring bean configuration is in fact a label <bean></bean>, the bean tag resist almost all of the configuration, and then the bean inheritance, abstraction, etc. are based on this label, master the Bean configuration, Detailed can make oneself have a relatively big promotion, especially for the novice (I also, hehe). The most basic bean configuration is as follows:
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" ></bean>
Here we simply use the HelloWorld class to instantiate, using the default construction method, which is equivalent to what we use:
HelloWorld tmp = new HelloWorld ();

But the difference is that in spring configuration there is only one instance during the entire application, which is a singleton, and of course the Singleton refers to an IOC container (spring) rather than the one we normally call the single-state pattern. Of course, spring can also be configured like this is not a singleton instance, such as we modify the following:
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" scope= "prototype" ></bean>
Notice the different color sections, so the configuration will indicate that every time you get an instance of HelloWorld from the spring container, we'll start with a new object, which is what we call a prototype, and the default in spring is Single State (singleton), Of course, for Web applications, it can also be configured as request, session, and other scopes. As to when to use what permission scope depends on the use of the application, such as in multi-threaded programs, whether the single state will have an impact on the program needs to be considered.
If the HelloWorld class does not have an empty construction method, only the following two construction methods, then how can we configure it?
......
Public HelloWorld (String str)
{
......
}
Public HelloWorld (date date, int i)
{
......
}
......
Since there is no default constructor, we need to write the constructor parameters in the bean configuration, as follows:
<!--using one parameter--
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" scope= "prototype" >
<constructor-arg><value>hello</value></constructor-arg>
</bean>
The above-mentioned use of a parameter, that is, the construction method with the string parameter, if you want to use the construction method with date and integral type, then the following configuration should be done:
<bean id= "Bean_date" class= "Java.util.Date"/>
<!--using two-parameter construction--
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" scope= "prototype" >
<constructor-arg ref= "Bean_date" ></constructor-arg>
<constructor-arg><value>345</value></constructor-arg>
</bean>
Note that in the above configuration we used the REF keyword, which is an object that represents the ID bean_date in the reference configuration file, and spring does the appropriate conversion for the type, such as converting 345 to a number. Of course, this is not a problem for the simple structure, if the situation is more complex, then the general recommendation is to use the serial number to calibrate, as follows:
<!--using two-parameter construction--
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" scope= "prototype" >
<constructor-arg index= "0" ref= "bean_date" ></constructor-arg>
<constructor-arg index= "1" ><value>345</value></constructor-arg>
</bean>
This way, it is convenient to use the Index property to indicate the location of the parameter, whether it is a spring construct or we can view it. Of course, spring also provides automatic lookup, which is dependent on the search function, but this I think people are still less useful, because this will make the entire configuration file looks very non-intuitive, and not clear, perhaps after a period of time to see the time do not know what it means, in the formal application project, It is better to organize and write the relationships of each bean.
All of the above is constructed to instantiate a bean, but sometimes we use Factory mode to get the bean. For Factory mode, we generally also use the static Factory mode and the instance Factory mode, which are also different in spring configuration. For the static factory pattern to instantiate the bean, our configuration is as follows:
<bean id= "bean_string" class= "Cn.qtone.test.TestFactory" factory-method= "Getbean"/>
Of course, we can also use the constructor parameters for a static factory-mode bean, which is not a word. The actual code corresponding to the bean configuration above should be:
......
public static Object Getbean ()
{
Return "Hello World";
}
......
Then spring, when instantiating a bean with ID bean_string, is fetched using the Testfactory Getbean () method, and the testfactory is not instantiated, which is obtained using a static method. For instance Factory mode, our configuration is a little bit different from the above, then we should configure two beans, one is the factory bean of the instance, and the other is the configuration of the bean we want to get, as follows:
<bean id= "Bean_factory" class= "Cn.qtone.test.TestBeanFactory"/>
<bean id= "Bean_helloworld" factory-bean= "Bean_factory" factory-method= "Gethello"/>
In the above configuration, the spring container will first instantiate a testbeanfactory, and then according to the class's method Gethello to get an instance of the bean, here we take the HelloWorld object as an example, the corresponding code should be as follows:
......
Public HelloWorld Gethello ()
{
return new HelloWorld ();
}
......
Notice that the Gethello method here is not a static method, but an instance method, so it must be instantiated before testbeanfactory can be called.
All of this is about how to instantiate a bean without mentioning the Bean's attribute injection. Although we can also be constructed by the time of the injection, but this does not only lose flexibility, but also a long list of structural parameters look at the eye pain ha, hehe. Of course, there is a case where we should use construct injection, that is, we must use construct injection when we want the injected object not to be modified by the outside world. For the bean attribute injection, take HelloWorld as an example, we can simply configure the following:
<bean id= "Bean_test" class= "Cn.qtone.test.HelloWorld" >
<property name= "Hello" value= "Hello!" "/>
<property name= "World" value= "Worlds"/>
<property name= "Date" ref= "Bean_date"/>
</bean>
The above configuration uses three attribute injections, the setter injection method in spring. Note the third attribute, which uses ref, to indicate that the setting parameter of the Date property is associated with the bean with the ID bean_date. Note that when using setter injection, the name of the property is not the full name of the method, but satisfies the naming of the JavaBean specification, that is, if the property name is XXX, then its corresponding method name should be: Setxxx (), except that the first character in XXX is not case-sensitive , the other is to be strictly differentiated. So in contrast to the above configuration, our HelloWorld method should be as follows:
......
public void Sethello (String hello)
{
......
}
public void Setworld (String world)
{
......
}
public void SetDate (date date)
{
......
}
......
The advantage of using setter injection is that it is clear that each injected parameter and meaning can be easily seen by name, which is one of the reasons why spring advocates using setter injection.

Spring's bean configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.