spring--IOC container details (RPM)

Source: Internet
Author: User

Spring, as a widely used and highly evaluated open source framework in the Java world, provides us with a lot of features that greatly facilitates our development. Here I introduce the IOC container and AOP concepts.

IOC (inversion of control) controlled inversion: the dependency between objects that would have been managed by the application is now given to the container management, which is called control inversion, which is given to the IOC container, and spring's IOC container is mainly implemented using DI. No active lookups are required, and object lookups, positioning, and creation are all managed by the container.

The popular point is that you don't create objects. We used to call a method of an object, first to new object. However, using an IOC container, the code does not directly connect to the object, but rather describes which object to use in the configuration file. The container is responsible for linking these together.

The object instantiation of an IOC container is implemented through a configuration file. In terms of this is called injection. There are two forms of injection, which are injected by constructing method and using setter injection. The specific injection form is as follows

is injected with a set method, adds a set method to the attribute, and assigns it

publicclass  Usermanagerimplimplements usermanager {

    private  Userdaouserdao;

    publicvoid setuserdao (Userdao Userdao) {

         this.userdao = Userdao;

    }

}

publicclass  Usermanagerimplimplements usermanager {

    private  Userdaouserdao;

    public usermanagerimpl (Userdao Userdao) {

         this.userdao = Userdao;

    }

<beanid= "Usermanager" class= " Com.bjpowernode.spring.manager.UserManagerImpl,

     < Propertyname= "Userdao" ref= "usrdao4oracle"/>

&NBSP;&NBSP;</BEAN>

<beanid= "Usermanager" class= " Com.bjpowernode.spring.manager.UserManagerImpl,

    < constructor-argref= "Userdao4mysql"/>

</BEAN>

set injection features:

        More similar to the traditional JavaBean, the programmer is easier to understand and accept, the setter way to set the dependency relationship is more intuitive and obvious;

         for complex dependencies, using construction injection can cause the constructor to be too bloated and difficult to read. When you create a bean instance, spring needs to instantiate all of its dependent instances at the same time, resulting in a decline in your functionality. Instead of using settings injection, this problem is avoided;

       especially if some properties are optional, the constructor of the multi-parameter is more awkward.

 ,

Construction method Injection features:

        construction injection can determine the injection order of dependencies in the constructor, prioritizing the priority injection of dependency.

<p line-height= 25px "align=" left ">        construction injection is more useful for beans that do not need to change dependencies Because there is no setter method, all dependencies are set within the constructor, so there is no need to worry about subsequent code corruption of dependencies.

       dependencies can only be set in the constructor, only the creator of the component can change the dependencies of the components. For the caller of the component, the dependencies inside the component are completely transparent and conform to the high cohesion principle;

&NBSP;

It is suggested that the injection strategy should be based on setting injection and auxiliary structure injection. As far as possible, there is no need to change the dependency of injection, the use of construction injection, while the other dependency of injection, then consider the introduction of set injection.

Here we say the injection of common attributes, but there are also some types of variables such as lists, arrays, and maps. Let's take a look at their injection form:

    <bean id= "Bean1" class= "Com.bjpowernode.spring.Bean1" > <property name= "strvalue" value= "hello_sp Ring "/> <!--<property name=" intvalue "value=" 123 "/>--&G              T                            <property name= "Intvalue" > <value>123</value> </property> <property name= "ListValue" > <list> &LT;VALUE&GT;LIST1&L t;/value> <value>list2</value> </list> </proper ty> <property name= "SetValue" > <set> &LT;VALUE&GT;SET1&L t;/value> <value>set2</value> </set> </property > <property name= "arrayvalue" > <list> <value>array 1</value> <value>array2</value> </list> &LT;/PROPERTY&G              T                      <property name= "Mapvalue" > <map> <entry key= "K1" value= "v1"/>              <entry key= "K2" value= "v2"/> </map> </property>   <property name= "DateValue" value= "December 14, 2009"/> </bean>

Not all types of editors are implemented in spring, and some types, such as time, are not implemented. We need to define it ourselves. How do I customize the property editor? First, you inherit the PropertyEditorSupport class, then overwrite the Setastext () method, and finally inject the custom property editor into spring

public class Utildatepropertyeditorextends PropertyEditorSupport {    private stringpattern;    @Override    publicvoid setastext (String text) throws IllegalArgumentException {        System.out.println ("--- Utildatepropertyeditor.setastext ()---> "+ text);        try {            Date date = new SimpleDateFormat (pattern). Parse (text);            This.setvalue (date);        } catch (ParseException e) {            e.printstacktrace ();            Thrownew illegalargumentexception (text);        }    }    Publicvoid Setpattern (String pattern) {        This.pattern = pattern;    }   }

Here is the pattern matching form, we are using set injection. The implementation in the configuration file is:

<bean id= "customeditors" class= "Org.springframework.beans.factory.config.CustomEditorConfigurer" >< Property Name= "Customeditors" ><map><entry key= "java.util.Date" ><bean class= " Com.bjpowernode.spring.UtilDatePropertyEditor "><property name=" pattern "value=" yyyy year mm DD Day "/></bean ></entry></map></property></bean>

As can be seen from the above, each class in the configuration file is identified by a bean tag and attributes are identified by property. If there are many attributes, the configuration file can be cumbersome. Is there a situation in which you can reduce some of the configuration file settings? It is true that if several beans have the same attributes, then these attributes can be abstracted. Like what:

<bean id= "Abstractbean" abstract= "true" >        <propertyname= "id" value= "/> <propertyname="        Name "value=" Zhangsan "/>        <propertyname=" Sex "value=" nan "/></bean>    <beanid=" Bean3 "class = "Com.bjpowernode.spring.Bean3" parent= "Abstractbean"/><beanid= "Bean4" class= "Com.bjpowernode.spring.Bean4 "Parent=" Abstractbean ">     <propertyname=" Age ">          <value>90</value>     </property ></bean>

BEAN3,BEAN4 has the same property, Id,name,sex, you can abstract it out of an abstract bean, and then specify its parent tag as an abstract bean in a specific bean.

We all know the regular expressions, which represent a number of different characters in a uniform format. There are similar features in the IOC. There are times when an object contains properties for other objects. If these attribute names have some relationship with name or type (Specific package name Class name), it is not possible to display the call. The IOC container automatically goes back to find. Such as:

 <beans ... default-autowire= "ByName"              > <!--<bean id= "bean2" class= "com.bjpowernode.spring.Bean2" > <property name= "bean3" ref= "bean3"/> <property name= "Bean4" > <ref bean= "b          Ean4 "/> </property> <property name=" Bean5 "ref=" Bean5 "/> </bean> --<bean id= "bean2" class= "com.bjpowernode.spring.Bean2"/> 
 <beans ... default-autowire= "Bytype"              > <!--<bean id= "bean2" class= "com.bjpowernode.spring.Bean2" > <property name= "bean3" ref= "bean3"/> <property name= "Bean4" > <ref bean= "b          Ean4 "/> </property> <property name=" Bean5 "ref=" Bean5 "/> </bean> --<bean id= "bean2" class= "com.bjpowernode.spring.Bean2"/> <bean id= "be an322 "class=" com.bjpowernode.spring.Bean3 "> <property name=" id "value=" "/> <prop" Erty name= "name" value= "Zhangsan"/> <property name= "Sex" value= "nan"/> </bean> 

The bean configuration implemented by the IOC container is the same as what we achieved in the new instance in the code. When we instantiate, we can use singleton mode, only one instance is running or multiple instances can be run. Do you have this configuration in the IOC container? Of course, that is the scope scope of the bean. Singleton the default value, each call to Getbean () is identical to the object obtained in the IOC container. That is, a single case. In the case of prototype, it is not the same for each call to Getbean () to get objects to the IOC container. That is equivalent to ordinary instantiation.
<bean id= "Bean1" class= "Com.bjpowernode.spring.Bean1" scope= "prototype"/>

Or

<bean id= "Bean1" class= "Com.bjpowernode.spring.Bean1" scope= "singleton"/>

With the IOC control reversal, the number of factory and Singleton is reduced, making the code hierarchy clearer. Spring's IOC container is a lightweight container that is not intrusive, does not need to rely on the container's API, and does not need to implement some special interfaces. and a reasonable design is best to avoid intrusion. The coupling in the code is reduced, the coupling is deferred to the configuration file, and changes are made easier to control.

Original address: http://www.open-open.com/lib/view/open1338175365089.html

spring--IOC container details (RPM)

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.