Home > Java > javaTutorial > Spring IOC container

Spring IOC container

大家讲道理
Release: 2017-08-19 13:46:19
Original
1537 people have browsed it

1. Introduction to Spring Framework

What is Spring?

Spring is an open source lightweight application development framework. The purpose is to simplify enterprise-level application development and reduce intrusion

The IOC and AOP applications provided by Spring can minimize the coupling of components, that is, decoupling, to facilitate future maintenance and upgrades of the system

Spring provides an overall solution for the system. In addition to the functions it provides, developers can also integrate applications with third-party frameworks and technologies, and can freely choose which technology to use for development

2. Container and Bean management

Introduction to Spring container

In Spring, any java class and javaBean are treated as beans. These beans are managed and applied through the container.

Spring container implements IOC and AOP mechanisms. These mechanisms can simplify the creation of Bean objects and the decoupling between Bean objects.

Spring container has two BeanFactory and ApplicationContext Type

(What is javaBean: a simple and standardized java object; when to use Spring: You can use it when you need to manage javaBean objects. Spring is one of the simplest object management solutions)

Instantiation of Spring container

ApplicationContext inherits from the BeanFactory interface and has more enterprise-level methods. It is recommended to use this type. The instantiation method is as follows:

//Load the configuration file instantiation in the file system

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

ApplicationContext ac = new FileSystemXmlApplicationContext(conf);

//Load the configuration file instantiation under the project classpath

String conf = "applicationContext.xml";

ApplicationContext ac = new ClassPathXmlApplicationContext(conf);

The use of Spring container

In essence, BeanFactory and ApplicationContext are just a high-level factory interface that maintains Bean definitions and interdependencies. We can access the bean definition through BeanFactory and ApplicationContext

First add the Bean definition in the container configuration file applicationContext.xml

Then after creating the BeanFactory and ApplicationContext container objects, call the getBean() method to obtain the instance of the Bean [getBean("identifier")]

Instancing of the Bean

There are three ways for the Spring container to create Bean objects:

-Use the constructor to instantiate

(The id or name attribute is used to specify the Bean name and is used to find the Bean object from Spring; class is used to specify the Bean type and will automatically call the parameterless constructor to create the object)

-Use static factory method to instantiate

(The id attribute is used to specify the Bean name, the class attribute is used to specify the factory type, and the factory-method attribute is used to specify the method for creating Bean objects in the factory. Methods that must be decorated with static)

-Use the instance factory method to instantiate

(id is used to specify the bean name, the factory-bean attribute is used to specify the factory Bean object, and the factory-method attribute is used to specify the method of creating the Bean object in the factory)

(Tell Spring the object creation rules, Spring Will help you create objects; based on configuration and default rules, reducing code writing)

Bean naming

Bean name:

In the Spring container, each Bean needs to have a name (i.e. identifier). The name can be specified using the id or name attribute of the element; the id attribute is smaller than the name Strict, uniqueness is required, special characters such as "/" are not allowed

Bean alias:

is a defined Bean, and to add another name reference, you can use

Bean scope:

Spring container is in When instantiating a bean, you can create Bean objects with the following scopes

1, singleton scope


In each Spring IOC A bean definition in the container corresponds to an object instance. The default item
configures the instance:

or


2、prototype


One bean definition corresponds to multiple object instances
Configuration instance:

or


3. request

request means that a new bean will be generated for each HTTP request, and the bean is only valid within the current HTTP request
When using request, session, and global session, you must first make the following configuration in the web.xml that initializes the web:


If you are using a web container with Servlet 2.4 and above, then you only need Just add the following ContextListener to the XML declaration file web.xml of the web application:
...org.springframework.web.context.request. RequestContextListener...

If it is a web container before Servlet2.4, then you have to use an implementation of javax.servlet.Filter :
.. requestContextFilter org.springframework.web.filter.RequestContextFilter requestContextFilter /*...< ;/web-app>
Then you can configure the scope of the bean:


4, session

session scope means that a new bean will be generated for each HTTP request, and the bean will only be generated during the current HTTP request. Valid within the session (in an HTTPSession, one bean definition corresponds to one instance, limited to the Web environment)
Configuration instance:
The premise is the same as the request configuration instance. After configuring the web startup file, you can configure it as follows:


5、global session

In a global HTTPSession, one bean definition corresponds to one instance, which is only meaningful in portlet-based Web applications. The Portlet specification defines the concept of global Session
Configuration instance:
and The premise of request configuration instance is the same. After configuring the web startup file, you can configure it as follows:

(The above Bean scope can be specified through the scope attribute defined by )

Bean life cycle callback

Specify the initialization callback method:

##

Specify the destruction callback method, only applicable to beans in singleton mode:

The default-init-method attribute in the top-level element can specify the initialization callback method for all in the container.

 

The default-destroy-method attribute in the top-level element can specify the destruction callback method for all in the container

 

Bean delayed instantiation

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

If you don’t want to To allow a singleton bean to be instantiated in advance when the ApplicationContext is initialized, you can use the lazy-init = "true" attribute of the element to change it

A lazy-initialized bean will be instantiated the first time it is used

In the top-level element The default-lazy-init attribute in the container can specify lazy instantiation characteristics for all in the container

Specify bean dependencies

When a bean has a dependency on another bean, you can use the depends-on attribute of the element to specify

When a bean is dependent on multiple When a bean has a dependency relationship, the depends-on attribute can specify multiple bean names, separated by commas

3. Container IOC application

IOC concept

The full name of IOC is Inversion of Control, translated as inversion of control;

IOC refers to the reversal of the acquisition method of objects in the program, from the original new method to creation and injection by a third-party framework. Third-party frameworks generally specify which specific implementation to inject through configuration, thereby reducing the coupling between objects

IOC can be divided into two types: dependency injection DI and dependency lookup depending on the implementation method

Spring container uses DI to implement IOC control. IOC is the foundation and core of Spring container

DI concept

The full name of DI is Dependency Injection, which is translated Injecting dependencies

The basic principle of DI is to connect objects that work together and have relationships through constructor parameters or method parameters. Therefore, the job of the container is to inject those dependencies when creating a bean

IOC is an idea, and DI is the main technical way to realize IOC

DI has two main injection methods, namely Setter injection and constructor injection

Setterr injection

After instantiating a bean by calling the parameterless constructor or parameterless static factory method, and calling the setter method of the bean, setter injection can be achieved

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 codes....

  }

In the container xml configuration, configure the injection parameters

 

 

 

 

Constructor injection

Constructor-based injection is done by calling a constructor with parameters It is implemented by the container. When the bean is instantiated, the container executes the corresponding constructor according to the parameter type

public class OracleUserDAO implements UserDAO{

 private JDBCDataSource dataSource;

 public OracleUserDAO(JDBCDataSource dataSource){

  this.dataSource = dataSource;

  }

  //Other code...

}

Specify injection according to constructor parameter index

 

 

 

 

 < ;constructor-arg index = "0" ref = "dataSource"/>

Autowiring

Spring IOC The container can automatically assemble (autowire) the association between cooperating beans. Autowire can be set for a single bean. The convenience of autowire is to reduce the injection configuration of xml

In the xml configuration file, you can Use the autowire attribute in the ;bean/> element to specify automatic assembly rules. There are five types of values.

The attribute value is no:Autowire is prohibited, and the default value is ;

The attribute value is byName:Automatically assemble based on the attribute name. This option will check the container and find a bean that is exactly the same as the attribute based on the name, and automatically assemble it with the attribute;

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

The attribute value is constructor: is similar to byType, except that it is applied to the constructor parameter;

The attribute value is autodetect:Determine whether to use the constructor or byType method for automatic detection through the bean class Assembly, if a default constructor is found, the byType method will be used

Configuration example:

 

In the above configuration, if there is a method Setter method that receives the UserDao type in UserService, Spring can automatically inject the userDAO object into it


The above is the detailed content of Spring IOC container. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template