[Spring Advanced Series | Part 4] Learn Bean management in Spring (based on xml configuration)

Preface

In previous studies, we know that a container is a concept of space, generally understood as a place that can hold objects. In the Spring container, it is usually understood as BeanFactory or ApplicationContext. We know that spring's IOC container can help us create objects. After the objects are handed over to spring for management, we do not need to manually create new objects.

So how does Spring manage Beans?

Insert image description here

1. Concept

In short, Spring beans are objects managed by the Spring framework at runtime. Spring beans are the basic building blocks of any Spring application. Most of the application logic code you write will be placed in Spring beans.

Spring bean management includes:

  • create an object
  • Provide dependencies (e.g. other beans, configuration properties)
  • Intercept object method calls to provide additional framework functionality
  • destroy an object

Spring beans are the basic concept of the framework. As a Spring user, you should have a deep understanding of this core abstraction.


2. Three ways to create Bean objects

2.1. Use the default constructor creation method

2.1.1. Define Bean

public class UserServiceImpl {
    
    
    
}

2.1.2. Configure beans in the main configuration file

<!-- 方式一:使用默认构造函数方式创建Bean   -->
<beans>
	<bean id="userService" class="cn.bdqn.UserServiceImpl"></bean>
</beans>

2.1.3. Test Bean

@Test
public void testUserService() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        // 2、从容器中根据id获取对象(bean)
        UserServiceImpl userService = (UserServiceImpl) ac.getBean("userService");

        // 3、打印bean
        System.out.println(userService);
}

2.1.4, Notes

This method uses a default constructor to create a bean. Assume that we add a constructor with parameters to UserServiceImpl, and an error will be reported when running. The reason isWhen we customize the constructor for a class, the Java compiler will not provide a default constructor without parameters for the class.

2.2. Use the instance method creation method in the factory

2.2.1. Define factory

// UserService的工厂,作用是创建UserServiceBean对象
public class UserServiceImplFactory {
    
    

    public UserServiceImpl createUserService(){
    
    
        return new UserServiceImpl();
    }
}

2.2.2. Define Bean

public class UserServiceImpl {
    
    
    
}

2.2.3. Configure beans in the main configuration file

<beans>
  	<!-- 方式二:使用工厂中提供的实例方法创建Bean   -->
  
	<!-- 第一步:把该工厂定义出来   -->
    <bean id="userServiceFactory" class="cn.bdqn.UserServiceImplFactory"/>
    <!-- 第二步:定义Bean(通过userServiceFactory中提供的实例方法)-->
    <bean id="userService" factory-bean="userServiceFactory" 
 						   factory-method="createUserService"/>
</beans>

2.2.4. Testing

@Test
public void testUserService() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        // 2、从容器中根据id获取对象(bean)
        UserServiceImpl userService = (UserServiceImpl) ac.getBean("userService");

        // 3、打印bean
        System.out.println(userService);
}

2.3. Use the static method creation method in the factory

2.3.1. Define factory

// UserService的工厂,作用是创建UserServiceBean对象
public class UserServiceImplFactory {
    
    

    public static UserServiceImpl createUserService(){
    
    
        return new UserServiceImpl();
    }
}

2.3.2. Define Bean

public class UserServiceImpl {
    
    

}

2.3.3. Configure beans in the main configuration file

<beans>
    <!-- 方式三:使用工厂中提供的静态方法创建Bean   -->

    <!-- 定义Bean(通过工厂类的静态方法创建)   -->
    <bean id="userService" class="cn.bdqn.UserServiceImplFactory" 
          				   factory-method="createUserService">
    </bean>
</beans>

2.3.4. Testing

@Test
public void testUserService() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        // 2、从容器中根据id获取对象(bean)
        UserServiceImpl userService = (UserServiceImpl) ac.getBean("userService");

        // 3、打印bean
        System.out.println(userService);
}

3. Scope of Bean Object

3.1. Description

​ Spring’s default scope (scope) for Bean is singleton [single case]

3.2. Scope type

  • singleton: singleton (default value), it will only be new once.

  • prototype: multiple instances, it will be new once it is used.

  • request: Acts on the request scope of web applications. After Spring creates this class, it saves this class in the request scope.

  • session: applied to the session scope of web projects. After Spring creates this class, it saves this class in the session scope.

  • global-session: The session scope (global session scope) that acts on the cluster environment. When it is not a cluster environment, it is the session.

3.3. Pay attention to details

The most commonly used in actual development issingletonandprototypeUse prototype when integrating struts2, and use singleton when integrating SpringMVC.

3.4. How to modify the scope of Bean

The scope attribute of the bean tag is used to specify the scope of the bean.

3.5. Testing

3.5.1. Test singleton

public class UserServiceImpl {
    
    
    
}
<beans>
	<bean id="userService" class="cn.bdqn.UserServiceImpl" />
</beans>
@Test
public void testUserService() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        // 2、从容器中根据id获取对象(bean)
        UserServiceImpl userService1 = (UserServiceImpl) ac.getBean("userService");
        UserServiceImpl userService2 = (UserServiceImpl) ac.getBean("userService");

        // 3、打印bean
        System.out.println(userService1 == userService2); // true
}

3.5.2. Test prototype multiple instances

public class UserServiceImpl {
    
    
    
}
<bean id="userService" class="cn.bdqn.UserServiceImpl" scope="prototype"/>
 @Test
public void testUserService() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        // 2、从容器中根据id获取对象(bean)
        UserServiceImpl userService1 = (UserServiceImpl) ac.getBean("userService");
        UserServiceImpl userService2 = (UserServiceImpl) ac.getBean("userService");

        // 3、打印bean
        System.out.println(userService1 == userService2); // false
}

4. Life cycle of Bean object

4.1. Singleton object

4.1.1. Description

Birth: The object is born when the container is created
Alive: The object is alive as long as the container is still there
Death: The container is destroyed and the object dies a>

4.1.2. Testing

4.1.2.1. Define Bean
public class UserServiceImpl {
    
    
    
    public UserServiceImpl(){
    
    
        System.out.println("对象的构造方法执行了");
    }

    public void init(){
    
    
        System.out.println("对象初始化了");
    }
    
    public void destroy(){
    
    
        System.out.println("对象销毁了");        
    }
}
4.1.2.2. Configure beans in the main configuration file
<beans>
	<bean id="userService" class="cn.bdqn.UserServiceImpl"
          scope="singleton" init-method="init" destroy-method="destroy"/>
</beans>
4.1.2.3. Testing
@Test
public void testUserService() throws Exception{
    
    
    // 1、读取主配置文件信息,获取核心容器对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

    ac.close();
}
// 结果:对于单例对象来说,只要容器创建了,那么对象就创建了。类似于立即加载。
4.1.2.4. Test results

The constructor of the object was executed
The object was initialized
The object was destroyed

Summary: The life cycle of a singleton object is the same as that of a container

4.2. Multiple instance objects

4.2.1. Description

Born: The spring framework creates it for us when we use the object
Alive: The object remains alive as long as it is in use.
Death: When the object is not used for a long time and is not referenced by other objects, it is recycled by Java's garbage collector

4.2.2. Testing

4.2.2.1. Define Bean
public class UserServiceImpl {
    
    
    
    public UserServiceImpl(){
    
    
        System.out.println("对象的构造方法执行了");
    }

    public void init(){
    
    
        System.out.println("对象初始化了");
    }
    
    public void destroy(){
    
    
        System.out.println("对象销毁了");        
    }
}
4.2.2.2. Configure beans in the main configuration file
<beans>
	<bean id="userService" class="cn.bdqn.UserServiceImpl"
          scope="prototype" init-method="init" destroy-method="destroy"/>
</beans>
4.2.2.3. Test 1
@Test
public void testUserService() throws Exception{
    
    
   	// 1、读取主配置文件信息,获取核心容器对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

    ac.close();
}
// 结果:什么都不输出,说明容器启动的时候,对于多例对象来说并不会创建
4.2.2.4, Test 2
@Test
public void testUserService() throws Exception{
    
    
   	// 1、读取主配置文件信息,获取核心容器对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

    UserServiceImpl userService = (UserServiceImpl) ac.getBean("userService");
    System.out.println(userService);
        
    ac.close();
}
/**
	结果:
		对象的构造方法执行了
		对象初始化了
	说明:
		对于多例对象来说,只有等到真正使用到该对象的时候才会创建。类似于懒加载。
**/

For beans with multiple instances, the Spring framework is not responsible for management.


5. Summary

Insert image description here


The above is the entire content of this article. If it is helpful to you, you can follow it for free. It would be better if you can follow it three times below. Your support is the motivation for me to update!

Insert image description here

Guess you like

Origin blog.csdn.net/m0_63947499/article/details/134577164