Bean related knowledge for getting started with Spring

Getting started with Spring - Bean related knowledge

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

image-20220809105418544

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

  1. presentation layer object (servelet)
  2. Business layer object (service)
  3. data layer object (dao)
  4. 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

image-20220809112132713

Then set it to private, and found that the constructor was also executed

image-20220809112244404

static factory

Create a factory class

image-20220809115844365

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

image-20220809115956831

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

image-20220809195208499


A modification of this method

Create a FactoryBean class

And let this class inherit the FactoryBean interface

image-20220809195706510

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

  1. 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...");
    }
}
  1. 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>
  1. run. It was found that only init was executed
  1. How to run the destroy function

    First change ApplicationContext applicationContext to ClassPathXmlApplicationContext

    1. Register shutdown hook

      applicationContext.registerShutdownHook();
      
    2. brute force shut down

      applicationContext.close();
      


Realize the bean life cycle according to the spring interface

This operation is performed at the service layer

  1. Inherit the InitializingBean and DisposableBean interfaces in the implementation class, and implement the destroy() and afterPropertiesSet() methods
  2. 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...");
    }
}

image-20220811103541610

Summarize

bean life cycle

  • Initialize the container
    1. create object (allocate memory)
    2. Execute the constructor
    3. Perform attribute injection (set operation)
    4. Execute the bean initialization method
  • use beans
    1. perform business operations
  • close/destroy container
    1. Execute the bean destruction method

Guess you like

Origin blog.csdn.net/qq_45842943/article/details/126313193