Home  >  Article  >  Java  >  What is the scope and life cycle of Bean in Java Spring

What is the scope and life cycle of Bean in Java Spring

PHPz
PHPzforward
2023-05-03 21:19:131511browse

1.Bean scope

1.1 Modified Bean case

What is the scope and life cycle of Bean in Java Spring

Reason: The default scope of Bean is Singleton mode, which means everyone uses the same object! When we learned the singleton mode before, we all knew that using singletons can improve performance to a great extent, so the scope of Beans in Spring is also the singleton singleton mode by default.

@Component
public class Users {

    @Bean
    public User user1(){
        User user = new User();
        user.setId(1);
        user.setName("Java");
        return user;
    }
}
@Component
public class Bean1 {

    @Autowired
    private User user;
    public User getUser(){
        System.out.println("Bean1对象未修改name之前 : "+user);
        user.setName("C++");
        return user;
    }
}
@Component
public class Bean2 {
    @Autowired
    private User user;

    public User getUser(){
        return user;
    }
}
public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        Bean1 bean1 = context.getBean("bean1",Bean1.class);
        System.out.println(bean1.getUser());
        Bean2 bean2 = context.getBean("bean2",Bean2.class);
        System.out.println(bean2.getUser());
    }
}

1.2 Why use singleton mode as the default scope

  • Only create one copy of the same resource to save space

  • There is no need to create and destroy objects too much, and the execution speed is improved

1.3 Scope

Scope is generally understood as: limiting the available scope of variables in the program is called Scope, or a certain area in the source code where variables are defined is called scope. The scope of
Bea refers to a certain behavior pattern of Bean in the entire framework of Spring, such as singletonSingle instance scope means that
means that Bean has only one copy in the entire Spring, and it is globally shared. Then when others modify this value, Then what another
person reads is the modified value.

In Spring, the scope of a bean is called a behavioral model, because in Spring's view, the singleton model is a behavior, which means that there can only be one bean in the entire Spring. share.

1.4 The 6 scopes of Bean

  • singleton:Single instance scope

  • prototype:Prototype scope (multiple instance scope)

  • request:Request scope

  • session:Session scope

  • ##application:Global scope

  • websocket:HTTP WebSocket scope

The last four are limited to SpringMVC, so at this stage we only learn the first two That’s it.

1.5 Setting the scope

Going back to the case just now, Bean2 hopes that the bean object obtained has not been modified, so we can modify the singleton mode to the multi-case mode.

Use @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

What is the scope and life cycle of Bean in Java Spring

What is the scope and life cycle of Bean in Java Spring

##Use @Scope ("prototype")

What is the scope and life cycle of Bean in Java Spring2. Spring execution process and Bean life cycle

What is the scope and life cycle of Bean in Java Spring

ps

: When the execution reaches the step of assembling the properties of the Bean, when the attribute injection is scanned, the class injection will be stopped first, and the attribute injection will be given priority, because the attribute may be used by subsequent methods. 2.1 Bean life cycle

The so-called life cycle refers to the entire life process of an object from birth to destruction. We call this process the life cycle of an object.

The life cycle of a Bean is divided into the following five parts:

    1. Instantiate the Bean (allocate memory space for the Bean)
  • 2. Setting properties (Bean injection and assembly)
  • 3. Bean initialization
  • implements various Aware notification methods, such as BeanNameAware, BeanFactoryAware, and ApplicationContextAware interface methods. For example, when Spring initializes a bean, it needs to assign an id (name) to the bean. If the beanName is successfully set, a beadNameAware notification will be generated; execute the BeanPostProcessor initialization pre-method (if this method is not overridden, follow the source code); execute the @PostConstruct initialization method, which will be executed after the dependency injection operation; execute the init specified by yourself -method method (if specified) is the method specified in the bean tag in Spring;

What is the scope and life cycle of Bean in Java SpringThis initialization method is different from the above one initialized with annotations. A product of the era, init is a product of the xml era, and @PostConstruct is a product of the annotation era. Priority: When Mr. Liang's methods exist at the same time, annotations are executed first, and then init is executed to execute the BeanPostProcessor initialization post-method (if this method is not overridden, follow the source code).

    4. Use Bean
  • 5. Destroy Bean various methods to destroy the container, such as @PreDestroy, DisposableBean interface method, destroy-method .

@PreDestroy和destroy-method的关系和初始化方法的两个关系差不多
优先级:@ProDestroy > 重写的DisposableBean接口方法 > destroy-method

执行流程图如下:

What is the scope and life cycle of Bean in Java Spring

ps:实例化和初始化的区别:实例化就是 分配内存空间。初始化,就是把我们一些参数,方法的具体实现逻辑给加载进去。

2.1.1生命周期演示

What is the scope and life cycle of Bean in Java Spring

What is the scope and life cycle of Bean in Java Spring

xml配置如下:

What is the scope and life cycle of Bean in Java Spring

Bean

public class BeanLifeComponent implements BeanNameAware {
    @PostConstruct
    public void PostConstruct(){
        System.out.println("执行@PostConstruct");
    }
    public void init(){
        System.out.println("执行bean-init-method");
    }
    public void use(){
        System.out.println("正在使用bean");
    }
    @PreDestroy
    public void PreDestroy(){
        System.out.println("执行@PreDestroy");
    }
    public void setBeanName(String s){
        System.out.println("执行了Aware通知");
    }
}

启动类

public class App2 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLifeComponent beanLifeComponent = context.getBean(BeanLifeComponent.class);
        beanLifeComponent.use();
        context.destroy();
    }
}

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"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="com.beans"></content:component-scan>
    <bean id="1" class="com.beans.BeanLifeComponent" init-method="init"></bean>
</beans>
2.1.2 为什么要先设置属性,在进行初始化
@Controller
public class TestUser {
    @Autowired
    private Test test;

    public TestUser(){
        test.sayHi();
        System.out.println("TestUser->调用构造方法");
    }
}

如果这段代码先执行了初始化,也就是其构造方法,会用到test对象,此时还没有设置属性,test就为null,会造成空指针异常。因此必须先设置属性,在进行初始化。

The above is the detailed content of What is the scope and life cycle of Bean in Java Spring. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete