After two years of writing code let's talk about Bean in Spring

  • 2021-11-24 01:34:51
  • OfStack

Directory (1) What is Bean (2) How to add Bean to Spring container (3) Scope of Bean (4) Common annotations of Bean 4.1 Conditional4.2 ComponentScan4.3 @ Import (5) Initialization and destruction of Bean 1, custom initialization and destruction methods 2, implementation through InitializingBean, DisposableBean interfaces 3, BeanPostProcessor (6) summary

(1) What is Bean

Bean in Spring is simply an Java object managed by Spring container. After we write a class, this class is only a simple Java class, which can be created by new. When we add this class to the Spring container, this class becomes Bean, which is managed by the Spring container and can be used by automatic injection.

(2) How to add Bean to an Spring container

Here are four common ways to add Bean.

1. @ Bean: The most common way to add Bean when writing a common class

2. @ ComponentScan + @ Controller @ Service @ Component @ Repository: After writing too much SpringBoot, 1 will be familiar with these.

3. @ Import: Inject Bean by importing

4. @ ImportBeanDefinitionRegister: Similar to Import, you can specify the name of Bean

(3) Scope of Bean

First of all, introduce the most basic @ Bean annotation. The @ Bean annotation declares that this class is an Bean. Before Spring5, most of the declarations will be put into the configuration file, and after Spring5, it can be completed through two annotations. Take the Teacher class as an example


public class Teacher {
}

@Configuration
public class MainConfig {
    @Bean
    public Teacher teacher(){
        return new Teacher();
    }
}

Without specifying @ Scope, all instances of bean are single-instance bean and are hungrily loaded (created when the container starts). Lazy loading (loaded on call) can be achieved through the annotation @ Lazy.


@Bean
//@Lazy
public User user(){
    return new User();
}

Specifying @ Scope as prototype represents multiple instances and is lazy loaded (created only when used)


@Bean
@Scope(value = "prototype")
public User user(){
    return new User();
}

List several other Bean scopes:


singleton   Singleton (default) 
prototype   Multiple instances 
request   Same as 1 Secondary request 
session   Same as 1 Session level 

(4) Commonly used annotations of Bean

There are several annotations that are often used with @ Bean1

4.1 Conditional

Conditional annotation means conditions, that is, it will take effect only if the conditions are met
For example, I configured Conditional in Bean:


@Bean
@Conditional(value = TeacherCondition.class)
public Teacher teacher(){
    return new Teacher();
}

The TeacherCondition code is as follows: true is returned if there is an student in Bean of Spring, otherwise false is returned


public class TeacherCondition implements Condition {
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        if (conditionContext.getBeanFactory().containsBean("student")){
            return true;
        }
        return false;
    }
}

The end result is that if TeacherCondition returns true, teacher, the bean, will be registered in the container, otherwise it will not be registered in the container.

4.2 ComponentScan

This annotation will appear at the same time as Controller, Service, etc. After adding annotations such as Controller and Service to a class, it is necessary to add annotations such as Controller and Service under the package scanned by ComponentScan and ComponentScan to the configuration class before it will take effect:


@Configuration
// The most basic scanning path mode 
//@ComponentScan(basePackages = {"com.javayz.testcompentscan"})
// Increased Filter The way of 
@ComponentScan(basePackages = {"com.javayz.testcompentscan"},includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class}),
        @ComponentScan.Filter(type = FilterType.CUSTOM,value = {TestFilterType.class})
},useDefaultFilters = false)
public class MainConfig {

    @Bean
    @Scope(value = "prototype")
    public User user(){
        return new User();
    }
}

Filter is a filter when scanning. For example, setting FilterType. ANNOTATION means that only the annotations set here will be scanned. FilterType. CUSTOM is a custom filter. TestFilterType class makes a layer 1 judgment: the class under the package name dao will be registered in the Bean container


public class TestFilterType implements TypeFilter {
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        // Object of the current class class Source information 
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        if (classMetadata.getClassName().contains("dao")){
            return true;
        }
        return false;
    }
}

4.3 @Import

@ Import can import third-party components from a container, or it can play a similar role as @ Bean1:


@Configuration
//@Import(value = {Teacher.class, Student.class})
//@Import(value = {MyImportSelector.class})
@Import(value = {MyBeanDefinitionRegister.class})
public class MainConfig {
}

The first way to import the corresponding class directly, here and directly write @ Bean effect 1


@Import(value = {Teacher.class, Student.class})

The second way is to import an ImportSelector object, and return the fully qualified name of the Bean to be imported through the selectImports method:


@Bean
//@Lazy
public User user(){
    return new User();
}
0

The third way is to inject Bean through BeanDefinitionRegister (you can specify the name of Bean)


@Bean
//@Lazy
public User user(){
    return new User();
}
1

The most commonly used scene of Import annotation is SpringBoot automatic injection, and @ Import annotation can be seen when exported from SpringBoot automatic injection source code.

(5) Initialization and destruction of Bean

When the container manages the life cycle of Bean, we can specify the initialization method and destruction method of Bean method by ourselves, so that an Bean can execute its own method during initialization and destruction.

1. Customize the initialization method and destruction method


@Bean
//@Lazy
public User user(){
    return new User();
}
2

When the singleton bean (singleton) container is started, the bean object is created, and when the container is destroyed, the destruction method of Bean is called.

For multi-instance bean, bean has not been created when the container is started, but will be created when the Bean is acquired, and the destruction of bean is not managed by the IOC container.

2. It is implemented through InitializingBean and DisposableBean interfaces

These two interfaces of Spring can also implement initialization and destruction functions.


public class Student implements InitializingBean, DisposableBean {
    public Student(){
        System.out.println("Student  Construction method ");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("Student Destruction ");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Student Initialization ");
    }
}
@Configuration
public class MainConfig {
    @Bean
    public Student student(){
        return new Student();
    }
}

3. BeanPostProcessor

BeanPostProcessor is called before and after initialization of all Bean


@Bean
//@Lazy
public User user(){
    return new User();
}
4

(6) Summary

Although the concept of Bean sounds simple, there are quite a few contents in it. IOC, the core of Spring, manages Bean. I'm a fish boy. I'll see you next time!


Related articles: