IOC configuration details
1.1. Vessel overview
**
ApplicationContext is the representative of Spring IoC container implementation. It is responsible for instantiating, configuring and assembling beans. The container obtains instructions about which objects to instantiate, configure, and assemble by reading the configuration metadata. Configuration metadata can be rendered using XML, Java annotations, or Java code. It allows you to handle interdependencies between application objects and other objects.
1.1.1. Configuration metadata
Configuration using xml
Simple and intuitive for getting started
Annotation based configuration:
@Compont(@serivce @controller @repository) @Autowride
Spring 2.5 supports annotation based metadata configuration:
Java based configuration used in SSM framework development: @ confirmation @ bean @ import
Since Spring 3.0, the functions provided by the Spring JavaConfig project have become part of the Spring core framework. Therefore, you can use Java configuration instead of XML configuration to define external bean s
Spring boot 1.0 has been supported since spring 4.0. After that, spring boot is completely developed in the way of javaConfig.
1.1.2. Instantiation of container
The object is created when the Spring container is created, not when it needs to be used
1.1.3. Use of containers
ApplicationContext is a high-level factory interface that can create bean definitions and handle interdependencies. It uses the method T getBean(String name, Class requiredType) to obtain container instances.
1//Create a spring context to load all bean s 2ApplicationContext context = new ClassPathXmlApplicationContext("service s.xml", "daos.xml"); 3 4//Get bean 5PetStoreService service = context.getBean("petStore", PetStoreService.cla ss); 6 7//Objects using bean s List<String> userList = service.getUsernameList();
1.2. bean overview
1.2.1. Named bean
<bean class="com.tuling.entity.User" id="user" name="user2 user3,user4;us er5"></bean>
Alias externally defined bean s
1.2.2. Instantiating beans
1 No default setting is required to instantiate using the constructor shortcoming:Cannot interfere with the instantiation process 2 Instantiate using static factory methods
<bean class="com.tuling.service.impl.UserServiceImpl" id="userService2"factory‐method="createUserServiceInstance" ></bean>
public static UserServiceImpl createUserServiceInstance(){return new UserServiceImpl();}
Instantiate using the instance factory method
<bean class="com.tuling.service.impl.UserServiceImpl" id="userService"factory‐bean="serviceFactory"factory‐method="createUserService" ></bean>
public class createUserService{public UserServiceImpl createUserFactory(){return new UserServiceImpl();} }
1.3. Dependence
1.3.1. Dependency injection
be based on setter Dependency injection of methods
<!‐‐be based on setter Dependency injection of methods .Property must be declared set method. name Is based on set For example, the method name is: setIdxx ‐> name="idxx"‐‐> <bean class="cn.tulingxueyuan.beans.User" id="user2"> <property name="idtuling" value="1"></property> <property name="username" value="zhangsan"></property><property name="realname" value="Zhang San"></property> </bean>
Constructor based dependency injection
<!‐‐Constructor based dependency injection .The custom constructor will be called to instantiate the object, and the default parameterless constructor will not be called . name It is based on the parameter name of the constructor, for example: User(String idxx) ‐> name="idxx" . name Attributes can be omitted, but pay attention to the location of parameters .If you have to stagger the position, you can use it name perhaps index perhaps type . index Is the subscript starting at 0 . type In the case of staggered positions, it can only be specified when the types are different ‐‐> <bean class="cn.tulingxueyuan.beans.User" id="user3"> <constructor‐arg name="username" value="lisi"></constructor‐arg> <constructor‐arg name="id_xushu" value="1"></constructor‐arg> <constructor‐arg name="realname" value="Li Si"></constructor‐arg> </bean>
use p Namespace simplification based on setter Attribute injection XML to configure use c Namespace simplification constructor based XML
<!‐‐Complex data type‐‐> <bean class="cn.tulingxueyuan.beans.Person" id="person" p:wife‐ ref="wife2"> <property name="id" value="1"></property> <property name="realName" value=""></property> <!‐‐set up null value‐‐> <property name="name"> <null></null> </property> <!‐‐When relying on others bean:inside bean inner bean <property name="wife"> <bean class="cn.tulingxueyuan.beans.Wife" > <property name="age" value="18"></property> <property name="name" value="Delireba"></property> </bean> </property>‐‐> <!‐‐When relying on others bean:Reference external bean <property name="wife" ref="wife"></property>‐‐> <property name="birthday" value="2020/05/20"></property> <property name="hobbies"> <list> <value>sing</value> <value>dance</value> <!‐‐If List The generic types are, for example: List<Wife> <bean>‐‐> </list> </property> <property name="course" > <map> <entry key="1" value="JAVA"> </entry> <entry key="2" value="HTML"> </entry> </map> </property> </bean> <!‐‐have access to p Namespace based simplification setter Property injection, which does not support collections‐‐> <bean class="cn.tulingxueyuan.beans.Wife" id="wife" p:age="18" p:name="Delireba" ></bean> <!‐‐have access to c Namespace to simplify constructor based attribute injection. It does not support collections‐‐> <bean class="cn.tulingxueyuan.beans.Wife" id="wife2" c:age="20" c:name="xxx"><!‐‐ <constructor‐arg name="age" value="18"></constructor‐arg>‐‐></bean>
1.3.2. Use attributes
<!‐‐use depends‐on You can set the first load Bean That is, control bean Loading order of‐‐> <bean class="cn.tulingxueyuan.beans.Person" id="person" depends‐ on="wife"></bean> <bean class="cn.tulingxueyuan.beans.Wife" id="wife"></bean>
1.3.3. Lazy load bean
<!‐‐use lazy‐init Set lazy load Default to false:stay spring Load (instantiate) when container is created true:When in use(getBean)To load (instantiate)‐‐> <bean class="cn.tulingxueyuan.beans.Person" id="person2" lazy‐ init="true"> <property name="id" value="1"></property> <property name="realName" value="Wu Yanzu"></property> <property name="name" value="Xu Shu"></property> </bean>
1.3.4. Automatic injection
When an object needs to refer to another object, in the previous configuration, we are through property Label for manual configuration, in fact spring It also provides a very powerful function It's automatic assembly, You can configure according to the rules specified by us in the following ways: default/no: No automatic assembly byName: Assemble by name, with attribute name as id Go to the container to find components and assign them Value, if not found, the assembly null byType: Assembly by type,Use the type of the attribute as the search basis to find this in the container Component, if there are multiple components of the same type bean Object, an exception will be reported. If it is not found, it will be assembled null constructor: Assemble according to the constructor, first according to the type of constructor parameters with parameters If not, it can be assembled directly null;If more than one is found by type, the parameter name is used as the id Continue matching, assemble if found, and assemble if not found null By will autowire-candidate Property is set to false,Avoid pair bean Define automatic loading Configuration, as described in the following section. By putting it<bean/> Elemental primary Property is set to true,Single bean Definition designated as primary Candidates.
<!‐‐**************************************be based on xml Automatic injection begin*********** ***************************************‐‐> <!‐‐Automatic injection: 1. bytype Automatic injection according to type(spring Will be based on bean The type of all object attributes inside, as long as it matches bean If a type matches the attribute type, it will be injected automatically 2. byname According to the properties setxxx To automatically match your name (spring Will be based on bean The properties of all objects inside set As long as it matches bean If a name matches the attribute name, it will be automatically injected 3. constructor Priority is given to the name. If the name does not match, it is matched according to the type. If the type matches If it is allocated to multiple, it will not be injected automatically be careful: bytype If you match two of the same types, an error will occur, so you must ensure that ioc There is only one corresponding type in the container bean byname The best match to the only one bean constructor Ensure that the constructor cannot contain extra parameters default:No automatic injection <bean class="cn.tulingxueyuan.beans.Person" id="person6" autowire="const ructor" > <property name="id" value="1"></property> <property name="realName" value="Wu Yanzu"></property> <property name="name" value="Xu Shu"></property> </bean> <bean class="cn.tulingxueyuan.beans.Wife" id="wife" p:age="18" p:name="Xiaoxin Technology" ></bean> <bean class="cn.tulingxueyuan.beans.Wife" id="QBL" p:age="60" p:name="Xiaoxin technology 1" ></bean> **************************************be based on xml Automatic injection end*************** ***********************************‐‐>
1.4. Scope of bean
1.4.1. Scope of singleton
1.4.2. Scope of prototype
<!‐‐Scope scope singleton default:The single case will only be in Ioc Create a container once prototype Multiple cases (prototype) bean)Every time you get it new A new bean‐‐> <bean class="cn.tulingxueyuan.beans.Person" id="person3" scope="prototype"> <property name="id" value="1"></property> <property name="realName" value="Wu Yanzu"></property><property name="name" value="Xu Shu"></property> </bean>
1.5. Characteristics of custom bean s
1.5.1. Lifecycle callback
1.5.2 initialization method callback and destruction method callback
1.5.3 gracefully close the Spring IoC container in non Web applications
/** *Lifecycle Callback * 1.Use the interface implementation method to realize the callback of the life cycle: * 1.1 Initialization method: implementation interface: InitializingBean overrides the afterpropertieset method to initialize the method that will be called automatically * 1.1 Destruction method: implementation interface: DisposableBean overrides the destruction method automatically when destroy ed Call method *When to destroy: close() when the spring container is closed *Or use the ConfigurableApplicationContext.registerShutdownHook method to close gracefully * * 2.Implement the callback of the life cycle by specifying the specific method: * Create two corresponding methods in the corresponding bean * init‐method="init" destroy‐method="destroy" */
1.6 ApplicationContextAware and BeanNameAware
1.7. Bean defined inheritance
<!‐‐bean Inherited one bean Inherit another bean have access to parent Property specifies the parent class bean If you want the parent class bean Cannot be instantiated abstract="true" <bean class="cn.tulingxueyuan.beans.Person" id="person4" abstract="true"> <property name="id" value="1"></property> <property name="realName" value="Wu Yanzu"></property> <property name="name" value="Xu Shu"></property> </bean> <bean class="cn.tulingxueyuan.beans.Person" id="person5" parent="person4" > <property name="realName" value="Lau Andy"></property> </bean>‐‐>
Spring creates third-party bean objects. In spring, many objects are single instance. In daily development, we often need to use some external single instance objects, such as database connection pool. Let's explain how to create third-party bean instances in spring. 1. Import pom file of database connection pool
1. Import pom file of database connection pool
<!‐‐ https://mvnrepository.com/artifact/com.alibaba/druid ‐‐> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <!‐‐ https://mvnrepository.com/artifact/mysql/mysql‐connector‐j ava ‐‐> <dependency> <groupId>mysql</groupId> <artifactId>mysql‐connector‐java</artifactId> <version>5.1.47</version> </dependency>
2. Write the configuration file ioc.xml
<?xml version="1.0" encoding="UTF‐8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance" xsi:schemaLocation="http://www.springframework.org/schema/beans htt p://www.springframework.org/schema/beans/spring‐beans.xsd"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="username" value="root"></property> <property name="password" value="123456"></property> <property name="url" value="jdbc:mysql://localhost:3306/demo"></pr operty> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> </bean> </beans>
3. Write test documents
public class MyTest { public static void main(String[] args) throws SQLException { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); DruidDataSource dataSource = context.getBean("dataSource", DruidDa taSource.class); System.out.println(dataSource); System.out.println(dataSource.getConnection()); } }