3 IOC Operation Bean Management (FactoryBean)
- spring has two types of beans, a normal bean and a factory bean(FactBean)
- Ordinary bean: defining the bean type in the configuration file is the return type
- Factory bean: The bean type defined in the configuration file can be different from the return type
- The first step is to create a class, let this class be a factory bean, and implement the interface FactoryBean
- The second step is to implement the methods in the interface and define the type of the returned bean in the implemented method
package com.wjiangquan.spring5.factorybean; import com.wjiangquan.spring5.collectiontype.Course; import org.springframework.beans.factory.FactoryBean; /** * @author weijiangquan * @date 2022/9/25 -18:40 * @Description */ public class MyBean implements FactoryBean<Course> { /** * Define the returned bean * @return * @throws Exception */ @Override public Course getObject() throws Exception { Course course = new Course(); course.setCname("asda"); return course; } @Override public Class<?> getObjectType() { return null; } @Override public boolean isSingleton() { return false; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <bean id="myBean" class="com.wjiangquan.spring5.factorybean.MyBean"></bean> </beans>
package com.wjiangquan.spring5.testDemo; import com.wjiangquan.spring5.collectiontype.Course; import com.wjiangquan.spring5.factorybean.MyBean; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author weijiangquan * @date 2022/9/25 -18:44 * @Description */ public class testBean { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); Course myBean = context.getBean("myBean", Course.class); System.out.println(myBean); } }
Note that an error will occur if this place is written like this
Probably means that the type does not match
4 Scope of beans
- In Spring, it can be set to be a single instance or multiple instances, the default is a single instance
A simple verification can be done
Get multiple times
@Test public void Bean1test(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); Book book = context.getBean("book", Book.class); Book book1 = context.getBean("book", Book.class); System.out.println("================="); System.out.println(book); System.out.println(book1); System.out.println("====================="); book.test(); }
It can be seen from the results that the objects obtained each time are the same (so the default is a single instance - but you can modify it in the configuration file)
4.1 Set up single instance, multiple instances
How to set single instance or multi-instance
(1) There is an attribute (scope) in the bean tag of the spring configuration file to set a single instance or multiple instances
(2) scope attribute value
The first value The default value, singleton, means a single instance object
The second value prototype
After modifying the bean file on the original basis
When testing again, it was found
The created object is different, now it is a multi-instance object
Difference between singleton and prototype:
The first singleton single instance, prototype multiple instances
Second, when the scope value is set to singleton, a single instance object will be created when the spring configuration file is loaded
When setting the scope value to prototype, instead of creating an object when loading the spring configuration file, create a multi-instance object when calling the getBean method
Note that in addition to the above two methods, there are also two types of request and session. It is enough to understand the two.
5 bean declaration cycle
1. Lifecycle
The process from object creation to object destruction
2.bean declaration cycle
(1) Create a bean instance through the constructor (no parameter construction)
(2) Set values for bean properties and references to other beans (call the set method)
(3) Call the initialization method of the bean (requires configuration)
(4) The bean is ready to use (the object is obtained)
(5) When the container is closed, call the bean's destroy method
3. Demonstrate the life cycle of a bean
Create an instance class Orders
package com.wjiangquan.spring5.bean; /** * @author weijiangquan * @date 2022/9/25 -21:49 * @Description */ public class Orders { //No-argument constructor public Orders() { System.out.println("The first step is to perform a no-parameter construction creation bean instance of"); } private String oname; public void setOname(String oname) { this.oname = oname; System.out.println("The first call set method to set the property value"); } //Create a method that executes the initial public void initMethod(){ System.out.println("The third step is to perform the initialization method"); } //Create a destroy method public void destroyMethod(){ System.out.println("The fifth step is to execute the method of destruction"); } }
xml file configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <bean id="orders" class="com.wjiangquan.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod"> <property name="oname" value="cell phone"></property> </bean> </beans>
Writing test code
@Test public void testBean1(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml"); Orders orders = context.getBean("orders", Orders.class); System.out.println("Step 4 Get bean instance object of"); System.out.println(orders); //Manually let the instance of the bean be destroyed context.close(); //close in this class ClassPathXmlApplicationContext } }
The verification of the running results, which is exactly as expected
On top of the two steps above, there are two more steps to deal with
5.bean post processor
After the bean declaration cycle is added, it is 7 steps, and if it is not added, it is five steps.
Demonstrate the effect of adding a post processor
(1) Create a class, implement the interface BeanPostProcessor, and create a post-processor
create a class
package com.wjiangquan.spring5.bean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * @author weijiangquan * @date 2022/9/25 -22:08 * @Description */ public class MyBeanPost implements BeanPostProcessor{ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Method executed before initialization"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("Method executed after reinitialization"); return bean; } }
Enable post processor in configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <bean id="orders" class="com.wjiangquan.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod"> <property name="oname" value="cell phone"></property> </bean> <!--Configure the post processor--> <bean id="myBeanPost" class="com.wjiangquan.spring5.bean.MyBeanPost"></bean> </beans>
Note: For the above writing, post processors will be added to all bean s
6 bean management xml method – autowiring
Note that xml injection is rarely used in practice, and annotations are generally used, but it is still necessary to understand
-
What is autowiring
(1) According to the specified assembly rules (property name or property type), Spring automatically injects the matching property value
-
Demonstrate the process of autowiring
Created two entity classes
package com.wjiangquan.spring5.outowire; /** * @author weijiangquan * @date 2022/9/25 -22:21 * @Description */ public class Dept { @Override public String toString() { return "Dept{}"; } }
package com.wjiangquan.spring5.outowire; /** * @author weijiangquan * @date 2022/9/25 -22:21 * @Description */ //Staff public class Emp { private Dept dept; public void setDept(Dept dept) { this.dept = dept; } @Override public String toString() { return "Emp{" + "dept=" + dept + '}'; } public void test(){ System.out.println(dept); } }
configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!--Implement automatic assembly--> <!-- bean Label properties autowire, Configure autowiring autowire There are two common values for properties: byName Inject based on property name, inject value bean of id same as class attribute name byTYpe Inject based on property type--> <bean id="emp" class="com.wjiangquan.spring5.outowire.Emp" autowire="byName"> <!--The following is the manual writing--> <!--<property name="dept" ref="dept"></property>--> </bean> <bean id="dept" class="com.wjiangquan.spring5.outowire.Dept"> </bean> </beans>
It should be noted that
7 Introducing an external properties file
When there are many attributes, it will be troublesome to write all of them. This section is mainly used to deal with this problem.
1. Directly configure the information of the database
(1) Configure the Druid connection pool
(2) Introduce Druid's jar package
<!--Configure the connection pool directly --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean>
2. Introduce an external property file to configure the database connection pool
(1) Create external property files, properties format files, and write database information
(2) Introduce the external properties property file into the spring configuration file
-
Introduce the context namespace
The red box part is the newly added part
- Introduce external properties files using tags in spring configuration files
<!--Import external properties file--> <context:property-placeholder location="classpath*:jdbc.properties"/> <!--Configure the connection pool directly --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClass}"></property> <property name="url" value="${prop.url]"></property> <property name="username" value="${prop.userName}"></property> <property name="password" value="${prop.password]"></property> </bean>
- Introduce external properties files using tags in spring configuration files
<!--Import external properties file--> <context:property-placeholder location="classpath*:jdbc.properties"/> <!--Configure the connection pool directly --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClass}"></property> <property name="url" value="${prop.url]"></property> <property name="username" value="${prop.userName}"></property> <property name="password" value="${prop.password]"></property> </bean>