search
HomeJavajavaTutorialWhat is the scope and life cycle of Bean in Java Spring

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:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

How does the underlying hardware architecture affect Java's performance?How does the underlying hardware architecture affect Java's performance?Apr 28, 2025 am 12:05 AM

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Explain why native libraries can break Java's platform independence.Explain why native libraries can break Java's platform independence.Apr 28, 2025 am 12:02 AM

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.