SoFunction
Updated on 2025-03-08

Explain what Spring Bean is in detail (example explanation)

Explain in detail what is Spring Bean?

What is Spring Bean

Spring Bean is an object instance managed by Spring IoC containers and is one of the basic components of the Spring framework. A bean can be any ordinary Java object or an object in a third-party library, such as Hibernate SessionFactory or MyBatis SqlSessionFactory.

The creation, assembly and management of Spring Beans are the responsibility of Spring IoC containers. After registering a bean in the container, the container is responsible for creating instances of the bean, managing the life cycle of the bean, and handling dependencies between the beans. Through Spring containers, loose coupling between objects can be achieved, which is convenient for testing, modular development, reuse, etc.

In Spring, beans are defined by configuration files or annotations. The configuration file is usually an XML or Java configuration class, which defines the bean by declaring the class name, scope, dependencies, attribute values, etc. of the bean. Annotations define a bean by adding specific annotations to the bean class. Whether it is an XML configuration file or annotation, it needs to be loaded and parsed by the Spring IoC container to create an instance of the bean and put into the container.

Spring How to register a bean

In Spring, there are many ways to register beans, including XML configuration files, Java configuration classes, and annotations.

Profile method: Create an instance of the bean and put into the container by defining a bean in an XML configuration file and then loading and parsing it by the Spring IoC container.

Example:

<!-- exist XML Define a configuration file Bean -->
<bean  class="">
   <property name="message" value="Hello, Spring!"/>
</bean>

Configuration class method: Define a bean by writing a Java configuration class, and then register the configuration class in the Spring IoC container. The configuration class is loaded and parsed by the container to create an instance of the bean and put into the container.

Example:

@Configuration
public class AppConfig {
    @Bean
    public ExampleBean exampleBean() {
        ExampleBean bean = new ExampleBean();
        ("Hello, Spring!");
        return bean;
    }
}

3. Annotation method: Define the bean by adding specific annotations to the bean class, and then scan and parse the annotations by the Spring IoC container to create an instance of the bean and put into the container.

Example:

@Component
public class ExampleBean {
    @Value("Hello, Spring!")
    private String message;
    // getter and setter methods
}

It should be noted that no matter which way you register a bean, the scope and dependencies of the bean need to be specified at the time of registration. At the same time, in order for Spring IoC containers to scan and parse beans correctly, you need to add corresponding configuration information to the Spring configuration file or Java configuration class.

The life cycle of spring bean

The life cycle of Spring Bean can be divided into the following stages:

  • Instantiation: When the container receives a request to create a bean, it instantiates a new bean object by calling the bean's constructor.
  • Set properties: Once the bean is instantiated, the container will set the property value of the bean through the bean's setter method.
  • Initialization: After all properties are set, the container will call the initialization method of the bean (if any). The initialization method of a bean can be the afterPropertiesSet() method that implements the InitializingBean interface, or the method specified using the init-method property.
  • Use: Once the bean is initialized, it can be used by the container.
  • Destruction: When the container is closed, it calls the bean's destruction method (if any). The method of destruction of a bean can be the destroy() method that implements the DisposableBean interface, or the method specified using the destroy-method property.

It should be noted that the initialization and destruction methods of beans are optional, and not all beans require these methods. In addition, if the Bean implements the DisposableBean and InitializingBean interfaces, these methods will be called before the corresponding interface methods.

The scope of spring bean

The scope of Spring Bean refers to the life cycle and visibility of using the bean instance in an application. Spring containers support the following five common bean scopes:

  • singleton: There is only one Bean instance in each Spring container. This instance is created when the container starts and is destroyed when the container closes. This is Spring's default bean scope.
  • prototype: A new instance is created every time a Bean instance is retrieved from a container. A container does not manage the life cycle of a bean instance, nor does it destroy the instance when the container is closed.
  • request: In an HTTP request, the container creates a bean instance for each request. This instance is destroyed after the request processing is completed.
  • session: In an HTTP session, the container creates a bean instance for each session. This instance is destroyed after the session ends.
  • global session: In a global HTTP session, the container creates a bean instance for each session. Applicable to portlet-based web applications only.

In addition to the above five common bean scopes, Spring also supports custom bean scopes, which can be implemented by implementing the Scope interface. Bean scope can be defined according to specific business needs for better performance and flexibility.

In actual development, singletons are usually used as the default bean scope because it saves resources and improves performance. However, for beans that require state-keep or thread-safe, such as beans with session and request scopes in web applications, or beans in multithreaded environments, other scopes need to be used to ensure correctness.

Detailed explanation of Spring Bean Scope Example

Preface

Hello everyone, I am god23bin. Today we will talk about the Bean scope (Scope) in the Spring framework.

What is the scope of a bean?

When we use XML as configuration metadata, we define a bean, as follows:

<bean  class="cn.">
	<!-- Collaborators write here... -->
</bean>

We wrote a Bean Definition, which is used to create instances of the defined class.

A bean definition, we can compare the definition of a class. You define a class, and you can create many instance objects based on this class.Similarly, the bean definition is the same, and many instance objects can be created based on this definition, but here is Spring for us to create, not manually.new 。We can understand these Bean object instances as objects in Spring IoC containers.

In the process of writing bean definitions, we can control the dependencies and corresponding values ​​of various beans, and inject these dependencies and values ​​into the objects created by the bean definition.Similarly, this process can also control the Scope (scope) of the object created by the bean definition. The scope of a bean defines the life cycle of a bean instance created in a container and its visibility in the application.

6 Bean scopes

Spring supports 6 bean scopes, 4 of which can only be perceived under web applications, as shown in the following table:

Scope illustrate
singleton (By default) Each Spring IoC container specifies a single bean-defined Scope as a single object instance.
prototype Expand a single bean-defined Scope to any number of object instances.
request Extends a single bean-defined Scope to the life cycle of a single HTTP request. That is, each HTTP request has its own bean instance, which is created on a single bean definition. Web-aware SpringApplicationContextvalid in the context.
session Expands a single bean-defined Scope to the life cycle of an HTTP session. Web-aware SpringApplicationContextvalid in the context.
application Expand the Scope defined by a single bean toServletContextDuring the life cycle. Web-aware SpringApplicationContextvalid in the context.
websocket Expand the Scope defined by a single bean toWebSocketlife cycle. Web-aware SpringApplicationContextvalid in the context.

1. Singleton Scope

singletonThe scoped bean has and only one instance object of this type in the Spring IoC container, that is, the singleton.

By default, if we do not specify the scope when writing bean definitions, then this bean object is a singleton.

<!-- Don't write Bean Scope of,The default scope is single case -->
<bean  class="cn."/>
<!-- Write scope,Here is a redundant writing method,use scope property -->
<bean  class="cn." scope="singleton"/>

This singleton object is stored in a cache area. Spring will return this cached object in subsequent requests or references.

In fact, the singleton's bean object in Spring isDifferent fromGang of Four The defined singleton pattern in the design pattern.

Design Pattern is a summary of the code development experience of predecessors and a series of routines to solve specific problems. It is not a syntax requirement, but a set of solutions to improve code reusability, maintainability, readability, robustness and security.

In 1995, GoF (Gang of Four, Gang of Four) collaborated on publishing the book "Design Pattern: The Basics of Reusable Object-Oriented Software", which included 23 design models, thus setting a milestone in the field of software design models, known as the "GoF Design Pattern".

Singleton patterns in design patterns are hard-coded so that each ClassLoader creates only one instance of a specific class.

andThe scope of Spring singleton refers to the singleton object of each IoC container that maintains its own bean.

2. Prototype Scope

The scope of bean isprototype, meaning prototype in Chinese, but in fact, it is omitted here.non-singleton, the full name of this scope isnon-singleton prototype scope,Right now"Scope of non-single-case prototypes」。

As the name suggests, the bean under this scope is not a singleton.This means that a bean is multiple cases, and each request or reference will create a new bean object.

Of course hereRequest or quoteIt means that when a non-single prototype bean is injected into another bean (the bean is referenced as an attribute), or we directly pass the container'sgetBean()When a method is called to request it, a new object will be created.

The scope of this bean is specified in XML asprototype

<bean  class="cn." scope="prototype"/>

In a bean under the prototype scope, Spring will not be responsible for the callback method of the bean's destruction cycle., If the bean has some important resources and wants to release these resources when the bean object is destroyed, then customization is requiredBeanPostProcessor(Bean's postprocessor), which holds references to the bean we need to clean up.

In some ways,prototypeThe function of beans in scope is to replacenewOperated.

The remaining 4 scopes

requestsessionapplicationandwebsocketscope Only when using Web-aware SpringApplicationContextImplementation (such asXmlWebApplicationContextOnly available when )

In short, these 4 scopes can generally be used in web applications with the help of Spring's Web module.

If you use these scopes with regular Spring IoC containers (such asClassPathXmlApplicationContext) will be used together and aIllegalStateException, prompts that there is an unknown Bean scope.

3. Request Scope

<bean  class="cn." scope="request"/>

Spring IoC containers are used for every HTTP requestloginControllerBean definition to createLoginControllerA new instance of Bean, thus achieving thisrequestScope.

You can change the internal state of the created instance as you wish, because from the sameloginControllerOther instances created in the bean definition will not see changes in these states. They are for a single request, and when the request completes processing, the beans involved in the request are discarded.

4. Session Scope

<bean  class="cn." scope="session"/>

Spring IoC containers are useduserPreferencesBean definition, in a single HTTPSessionCreate a new one within the life cycleUserPreferencesBean example.

andrequestLike the scope's bean, you can change the internal state of the created instance as you wish, and you need to know other HTTPSessionThe instance is also used from the sameuserPreferencesInstances created in bean definitions, they do not see changes in these states because they are specific to a single HTTPSession. When HTTPSessionWhen it is finally discarded, it will act on that specific HTTPSessionThe bean was also discarded.

5. Application Scope

<bean  class="cn." scope="application"/>

Spring containers are used once for the entire web applicationappPreferencesBean definition to createAppPreferencesA new instance of Bean.

This is a bit similar to Spring's singleton bean, but differs in two important aspects.

It's everyServletContextSingleton, not every SpringApplicationContext(There may be several in any given web application).

6. WebSocket Scope

This involves WebSocket, and will not be discussed for now. Let's fill in the pit later~

Dependencies between beans of different scopes

What is discussed here is generallySingleton scoped beansandPrototype scoped beansDependencies between them.

Now for example, suppose there are two Java classes handed over to Spring IoC container management, namely the SingletonBean class and the PrototypeBean class.

Where SingletonBean is a singleton scoped bean, and PrototypeBean is a prototype scoped bean.

Then when:

  • When the SingletonBean's dependency is a PrototypeBean, the PrototypeBean object will only be initialized once and injected into the SingletonBean, so that the PrototypeBean will not have the effect of prototype scope.
  • When the dependency of PrototypeBean is SingletonBean, each time the PrototypeBean object is created, these objects depend on a singleton object, and there is no problem at this time.

Method Injection

Spring provides aMethod Injection(Method Injection) mechanism toSolve the issue of creating only one instance when a prototype scoped bean is injected into a singleton scoped bean.

Method injection allows to get one every time a method is calledNew prototype scoped bean instances

Method injection is achieved by defining a method in SingletonBean that returns a PrototypeBean instance. In this way, where you need to use PrototypeBean each time, you can get a new instance by calling the method.

Here is an example of using method injection to resolve Prototype Bean scope:

public abstract class SingletonBean {
    public abstract PrototypeBean getPrototypeBean();
    public void doSomething() {
        PrototypeBean prototypeBean = getPrototypeBean();
        // Use Prototype Bean to do it    }
}
public class PrototypeBean {
    // Definition of Prototype Bean}

In the above example,SingletonBeanis an abstract class where an abstract method is declaredgetPrototypeBean(), this method returns aPrototypeBeanExample. existdoSomething()In the method, by callinggetPrototypeBean()Method to get a newPrototypeBeaninstance, in order to be calleddoSomething()Use different instances when using.

Then, it can be implemented through specific subclasses.SingletonBean, and realizegetPrototypeBean()Method to return the correspondingPrototypeBeanExample.

Through method injection, each calldoSomething()A new method will be obtainedPrototypeBeanInstance, thus solving the issue of creating only one instance when injecting Prototype beans into Singleton Beans.

It should be noted that method injection requires special configuration when configuring files or using annotations. The specific configuration methods are basically as follows.

1. XML configuration method

Of course, the above example is an abstract class, and it is OK not an abstract class, for example:

public class SingletonBean {
    // Method injection, Spring will help us return this object, just write it as null    public PrototypeBean getPrototypeBean() {
        return null;
    }
    public void doSomething() {
        PrototypeBean prototypeBean = getPrototypeBean();
        // Use Prototype Bean to do it    }
}
public class PrototypeBean {
    // Definition of Prototype Bean}

Next, there is no method injection that cannot be implemented above alone. It also needs to be combined with configuration metadata. It is now used in XML configuration files.<lookup-method />Tags to implement method injection.

<bean  class="cn.">
    <lookup-method name="getPrototypeBean" bean="prototypeBean"/>
</bean>
<bean  class="cn." scope="prototype"/>

In the above configuration example,singletonBeanis a singleton bean, by<lookup-method />The tag specifies a namegetPrototypeBeanmethod and reference a prototype BeanprototypeBean

At runtime, every callgetPrototypeBeanWhen the method is used, a new one will be returnedprototypeBeanExample.

2. Annotation configuration method

use@LookupAnnotation to implement method injection.

@Component
public class SingletonBean {
    private PrototypeBean prototypeBean;
    @Lookup
    public PrototypeBean getPrototypeBean() {
        return null; // In fact, it will generate a specific implementation by Spring    }
    // Other codes...}
@Component
@Scope("prototype")
public class PrototypeBean {
    // Specific prototype Bean implementation}

In the example above,SingletonBeanUsed@LookupThe annotation marks a name calledgetPrototypeBeanMethod. At runtime, Spring will generate a concrete implementation for this method to implement method injection.

Summarize

A brief summary:

The scope of a bean can be specified when the bean is defined. It is a singleton by default. Multiple-case beans are the so-called prototype scope.

There are 6 scopes that need to be familiar with, 4 of which are scopes that can only be found under Spring IoC (application context) with web-aware capabilities.

For the problem of singleton beans relying on prototype beans, they can be solved through method injection. There are two writing methods to implement method injection, one is XML and the other is annotation.

This is all about this article about Spring Bean Scope. For more information about Spring Bean Scope, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!