Spring IOC Container

Source: Internet
Author: User

Introduction to the 1.Spring framework

What is Spring?

Spring is an open-source, lightweight application development framework designed to streamline enterprise application development and reduce intrusion

Spring provides IOC and AOP applications that minimize component coupling, i.e. decoupling for future maintenance and upgrades of the system

Spring provides a holistic solution for the system, which allows developers to leverage the capabilities they provide, as well as integrate with third-party frameworks and technologies, with the freedom to choose which technology to use for development

2. Container and Bean Management

Introduction to Spring Containers

In spring, any Java class and JavaBean are treated as beans, and these beans are managed and applied through the container

The spring container implements IOC and AOP mechanisms that simplify the decoupling between bean object creation and Bean objects

Spring containers have two types of beanfactory and ApplicationContext

(What is JavaBean: A simple specification of Java objects, when to use spring: when you need to manage JavaBean objects, and spring is one of the most concise object management scenarios)

Instantiation of the Spring container

ApplicationContext inherits from the Beanfactory interface, has more enterprise-class methods, it is recommended to use this type, the instantiation method is as follows:

Loading configuration file instantiation in the file system

String conf = "C:\applicationContext.xml";

ApplicationContext ac = new Filesystemxmlapplicationcontext (conf);

Configuration file instantiation under load project Classpath

String conf = "Applicationcontext.xml";

ApplicationContext ac = new Classpathxmlapplicationcontext (conf);

Use of spring containers

Essentially, beanfactory and ApplicationContext are just a high-level factory interface that maintains bean definitions and interdependencies. With Beanfactory and ApplicationContext we can access the bean definition

First, add the bean definition in the container configuration file Applicationcontext.xml

<bean id = "identifier" class = "bean Type"/>

Then, after creating the Beanfactory and ApplicationContext container objects, call the Getbean () method to get the instance of the Bean [Getbean ("identifier")]

Instantiation of the Bean

The spring container creates a bean object in the following three ways:

-Instantiate with constructor

<bean id = "CALENDAROBJ1" class = "Java.util.GregorianCalendar"/>

<bean id = "CALENDAROBJ2" class = "Java.util.GregorianCalendar"/>

(The ID or Name property is used to specify the bean name, which is used to find the Bean object from spring; class is used to specify the bean type, and the parameterless constructor is automatically called to create the object)

-Instantiate using static Factory method

<bean id = "CALENDAROBJ2" class = "Java.util.Calendar" Factory-method = "getinstance"/>

(The id attribute is used to specify the bean name, the class attribute is used to specify the factory type, and the Factory-method property is used to specify the method for creating the Bean object in the factory, which must be decorated with static)

-Instantiate using instance factory method

<bean id = "CALENDAROBJ3" class = "Java.util.GregorianCalendar"/>

<bean id = "Dateobj" Factory-bean = "calendarObj3" Factory-method = "GetTime"/>

(ID is used to specify the bean name, the Factory-bean property is used to specify the factory bean object, and the Factory-method property is used to specify how the Bean object is created in the factory)

(The object creation rule tells Spring,spring to help you create the object; it reduces the writing of the code based on the configuration and default rules)

Name of the Bean

Name of the Bean:

In the spring container, each bean needs to have a name (that is, an identifier), which can be specified with the ID of the <bean> element or the name attribute; The id attribute is stricter than name, requires uniqueness, and does not allow special characters such as "/"

the name of the Bean :

For a defined bean, add another name reference, and you can use <alias> to specify

<alias name = "FromName" alias = "ToName"/>

Scope of the Bean:

Spring container When you instantiate a bean, you can create a bean object of the following scope

1. Singleton Scope


In each spring IOC container, a bean definition corresponds to an object instance, and the default item
Configuration instance:
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "singleton"/>
Or
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" singleton= "true"/>

2, prototype


A bean definition corresponds to multiple object instances
Configuration instance:
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "prototype"/>
Or
<beanid= "Role" class= "Spring.chapter2.maryGame.Role" singleton= "false"/>

3. Request

Request indicates that a new bean will be generated for each HTTP request, and that the bean is valid only within the current HTTP requests
When the request, session, global session is used, the following configuration is first done in Web. XML, which initializes it:


If you are using a Web container of servlet 2.4 and above, you only need to add the following contextlistener to the Web application's XML declaration file:
<web-app>...<listener><listener-class> org.springframework.web.context.request.requestcontextlistener</listener-class></listener>...</ Web-app>

If you are Servlet2.4 a previous web container, then you need to use a Javax.servlet.Filter implementation:
<web-app&gt, .... <filter> <filter-name>requestContextFilter</filter-name> <filter-class> Org.springframework.web.filter.requestcontextfilter</filter-class></filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern></ Filter-mapping>...</web-app>
You can then configure the scope of the bean:
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Request"/>

4. Session

The session scope indicates that a new bean is generated for each HTTP request, and that the bean is valid only within the current HTTP session (in one httpsession, a bean definition corresponds to an instance, Web environment only)
Configuration instance:
As with the request configuration instance, configuring the Web boot file can be configured as follows:
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Session"/>

5. Global session

In a global httpsession, a bean definition corresponds to an instance that only makes sense in a portlet-based Web application, and the Portlet specification defines the concept of a global session
Configuration instance:
As with the request configuration instance, configuring the Web boot file can be configured as follows:
<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Global Session"/>

(The bean scope above can be specified by the scope property defined by <bean>)

The Bean's life cycle callback

Specify the initialization callback method:

<bean id = "Examplebean" class = "Com.foo.ExampleBean" Init-method = "Init" >

</bean>

Specifies that the destroy callback method applies only to Singleton-mode beans:

<bean id = "Examplebean" class = "Com.foo.ExampleBean" Destroy-method = "Destroy" >

</bean>

The Default-init-method property in the top-level <beans/> element allows you to specify the initialization callback method for the container all <bean>

<beans Default-init-method = "Init" >

<bean id = "Examplebean" class = "Com.foo.ExampleBean"/>

</beans>

In the top-level <beans/> element of the Default-destroy-method property, you can destroy the callback method for all <bean> specified containers

<beans Default-destroy-method = "Destroy" >

<bean id = "Examplebean" class = "Com.foo.ExampleBean"/>

</beans>

Bean deferred instantiation

The default behavior implemented in ApplicationContext is to instantiate all singleton beans in advance at startup

If you do not want a singleton bean to be instantiated in advance of applicationcontext initialization, you can use the <bean> element's Lazy-init = "true" property to change

A deferred initialization bean will be instantiated the first time it is used

<bean id = "Examplebean" Lazy-init = "true" class = "Com.foo.ExampleBean"/>

The Default-lazy-init property in the top-level <beans/> element allows you to specify deferred instantiation attributes for all <bean> of a container

Specifying bean dependencies

When a bean has a dependency on another bean, you can use the Depends-on property of the <bean> element to specify

<bean id = "Beanone" class = "Examplebean" depends-on = "Manager"/>

<bean id = "Manager" class = "Managerbean"/>

When a bean has a dependency on multiple beans, the Depends-on property can specify multiple bean names, separated by commas

<bean id = "Beanone" class = "Examplebean" depends-on = "Manager1,manager2"/>

3. IOC Application of containers

IOC concept

The IOC full name is inversion of control, which is translated as controlled inversion;

IOC refers to the way in which objects in a program are acquired in reverse, created by the original new method, and transformed into a third-party framework created, injected. A third-party framework typically specifies which specific implementation to inject by configuration, thus reducing the coupling between objects

IOC can be divided into two types of dependency Injection Di and dependency lookup, depending on the implementation method.

The spring container is a di approach to IOC control, and the IOC is the Foundation and core of the spring container.

DI concept

Di full name is Dependency injection, which is translated as dependency injection

The basic principle of Di is to connect objects that work together, through construction method parameters or method parameters, so that the container's job is to inject those dependencies when the bean is created.

IOC is a kind of thought, and Di is the main technical way to realize IOC

There are two main ways to inject di: Setter injection and constructor injection

Setterr Injection

After the bean is instantiated by calling the parameterless constructor or the parameterless static factory method, the setter method of the bean is invoked to enable the injection of the setter mode.

public class jdbcdatasource{

Private String driver;

public void Setdriver (String driver) {

try{

Class.forName (driver);

This.driver = driver;

}catch (Exception e) {

throw new RuntimeException (e);

}

}

Other code ....

}

In the container XML configuration, configure the injection parameters

<bean id = "DataSource" class = "Org.dao.JDBCDataSource" >

<property name = "Driver" value = "Oracle.jdbc.OracleDriver"/>

<property name = "url" value = "Jdbc.oracle:thin: @localhost: 1521:xe"/>

<property name = "User" value = "OpenLab"/>

<property name = "PWD" value = "open123"/>

</bean>

Constructor injection

The constructor-based injection is implemented by invoking a constructor with parameters, and the container executes the corresponding constructor based on the parameter type when the bean is instantiated

public class Oracleuserdao implements userdao{

Private Jdbcdatasource DataSource;

Public Oracleuserdao (Jdbcdatasource dataSource) {

This.datasource = DataSource;

}

Other code .....

}

Specify injection by constructor parameter index

<bean id = "DataSource" class = "Org.dao.JDBCDataSource" >

<property name = "Driver" value = "Oracle.jdbc.OracleDriver"/>

<property name = "url" value = "Jdbc:oracle:thin: @localhost: 1521:xe"/>

<peoperty name = "User" value = "OpenLab"/>

<peoperty name = "PWD" value = "open123"/>

</bean>

<bean id = "Userdao" class = "Org.dao.OracleUserDAO" >

<constructor-arg index = "0" ref = "DataSource"/>

</bean>

Automatic assembly

The Spring IOC container can automatically assemble (autowire) the association between the beans, Autowire can be set for a single bean, and Autowire is convenient to reduce the XML injection configuration

In the XML configuration file, you can use the Autowire property in the <bean/> element to specify automatic assembly rules, with a total of five types of values

The property value is no: automatic assembly is forbidden, default value;

The property value is byname: automatically assembled according to the property name, this option examines the container and finds the bean that exactly matches the attribute based on its name, and automatically assembles it with the attribute;

The property value is Bytype: If there is a bean in the container that is the same as the specified property type, it will be automatically assembled with that property;

The property value is constructor: similar to Bytype, except that it is applied to constructor parameters;

The property value is AutoDetect: The Bean class is used to determine whether automatic assembly is done using constructor or Bytype, and if the default constructor is found, the Bytype method is used

Example configuration:

<bean id = "Userdao" class = "Org.dao.OracleUserDAO" >

<constructor-arg index = "0" ref = "DataSource"/>

</bean>

<bean id = "UserService" class = "org.service.UserService" Autowire = "Bytype"/>

The above configuration, in UserService if there is a method setter method that receives the Userdao type, spring can automatically inject the Userdao object in

(Self-summary, for reference only.) )

Spring IOC Container

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.