Getting started with Spring - Bean related knowledge
Article Directory
1 Bean configuration
1.1 Configure an alias for the bean
You only need to introduce the name attribute in the configuration file. There can be multiple aliases in the name, and you can use spaces, commas and semicolons to separate them.
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="BookDao" class="com.demo.dao.impl.BookDaoImpl"></bean>
<bean id="BookService" name="service service2 service3" class="com.demo.service.impl.BookServiceImpl">
<property name="bookDao" ref="BookDao"></property>
</bean>
</beans>
After configuration, call service2 to view the running results
1.2 Scope of Bean
When controlling bean creation, whether the object is a singleton
Run the following code to see if the addresses of the two objects are the same, to see if they are the same object. The result of the operation is the same address, indicating that the bean created by spring for us by default is a singleton
How to configure a non-singleton, in the configuration file, add the scope attribute. There are two options, namely: property type (non-singleton) singleton (singleton), the default is singleton
After setting the attribute to propertytype, run it again and find that there are two objects created
Which beans are suitable for singletons
- presentation layer object (servelet)
- Business layer object (service)
- data layer object (dao)
- tool object
not suitable for singleton
- The domain object (domain) that encapsulates the entity
2 Bean instantiation
2.1 Construction method
No parameter construction
In the implementation class of BookDao, create a no-argument constructor for it, first set it to public, and find that the constructor executes
Then set it to private, and found that the constructor was also executed
static factory
Create a factory class
When configuring xml, class configures the factory class name
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="OrderDao" class="com.demo.factory.OrderDaofactory" factory-method="getOrderDao"></bean> </beans>
Create an object to test
instance factory
After you have an instance factory class, you must first create an object and then refer to it
instance factory
public class UserDaofactory {
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
startup class
import com.demo.dao.UserDao;
import com.demo.factory.UserDaofactory;
public class AppForInstanceUser {
public static void main(String[] args) {
//创建实例工厂对象
UserDaofactory userDaofactory = new UserDaofactory();
//通过实例工厂对象创建对象
UserDao userDao = userDaofactory.getUserDao();
userDao.test();
}
}
how to use this method
The configuration file was changed to
<bean id="userFactory" class="com.demo.factory.UserDaofactory"></bean> <bean id="userDao" factory-bean="userFactory" factory-method="getUserDao"></bean>
operation result
A modification of this method
Create a FactoryBean class
And let this class inherit the FactoryBean interface
Configuration xml, class points to FactoryBean
<!-- 改良的方法配置-->
<bean id="userDao" class="com.demo.factory.UserDaoFactoryBean"></bean>
3 Bean life cycle
life cycle
The complete process from creation to demise
bean life cycle
The overall process of beans from creation to destruction
bean lifecycle control
Some things to do after the bean is created and before it is destroyed
- Create an initialization function and a destruction function in the implementation class of dao
import com.demo.dao.BookDao;
public class BookDaoImpl implements BookDao {
@Override
public void test() {
System.out.println("BookDao is running...");
}
//bean初始化对应的操作
public void init() {
System.out.println("init...");
}
//bean销毁前对应的操作
public void destory() {
System.out.println("destory...");
}
}
- Declare the initialization function and destruction function in the configuration file
<bean id="BookDao" class="com.demo.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"></bean>
- run. It was found that only init was executed
How to run the destroy function
First change ApplicationContext applicationContext to ClassPathXmlApplicationContext
Register shutdown hook
applicationContext.registerShutdownHook();
brute force shut down
applicationContext.close();
Realize the bean life cycle according to the spring interface
This operation is performed at the service layer
- Inherit the InitializingBean and DisposableBean interfaces in the implementation class, and implement the destroy() and afterPropertiesSet() methods
- run
Why is the initialization method of the inherited interface not called init, but after set
Write the output content in the set function and execute it
import com.demo.dao.BookDao;
import com.demo.dao.impl.BookDaoImpl;
import com.demo.service.BookService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
//删除业务层中使用new的方式创建到对象
private BookDao bookDao;
@Override
public void test() {
System.out.println("BookService is running...");
bookDao.test();
}
//提供对应的set方法
public void setBookDao(BookDao bookDao) {
System.out.println("set...");
this.bookDao = bookDao;
}
@Override
public void destroy() throws Exception {
System.out.println("Service destory...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Service init...");
}
}
Summarize
bean life cycle
- Initialize the container
- create object (allocate memory)
- Execute the constructor
- Perform attribute injection (set operation)
- Execute the bean initialization method
- use beans
- perform business operations
- close/destroy container
- Execute the bean destruction method