Want to become a Spring guru? First understand these 6 ways to add beans

Automatic scanning (Component Scanning)

Auto-scanning is a way for the Spring container to automatically find and load beans. In Spring, you can use annotations to mark a class as a Bean, for example, use @Component, @Service, @Repository or @Controller to mark a class. When the application starts, the Spring container scans all classes marked with these annotations in the project, instantiates them and puts them into the container.

@Component
public class MyBean {
    private String name;
    // 省略 getter/setter 方法
}

// 在 Spring 配置文件中开启自动扫描
<context:component-scan base-package="com.example" />

// 在需要使用 MyBean 的地方注入即可
@Autowired
private MyBean myBean;

Advantages: Automatic scanning can easily gather all the beans that need to be managed, and does not need to manually configure the information of each bean, reducing the amount of code and configuration time.

Disadvantages: Automatic scanning is easy to load classes that do not need to be managed, resulting in a large number of useless beans in the container, reducing the performance of the application.

XML configuration file

XML configuration file is the earliest and most classic configuration method of Spring. Define beans in XML files, specify their class names, attributes, and dependencies, and then load them into the Spring container through the configuration file loader.

<!-- 在 XML 配置文件中定义 Bean -->
<bean id="myBean" class="com.example.MyBean">
    <property name="name" value="John" />
</bean>

Advantages: XML configuration files can express the information of each Bean very clearly, including class names, attributes, dependencies, etc., which is convenient for management and maintenance.

Disadvantages: XML configuration files are lengthy, cumbersome to write, and not easy to maintain. At the same time, due to the need to manually write configuration files, errors are prone to occur, and additional testing and debugging work is required.

 

Java configuration class

The Java configuration class is a new configuration method introduced by Spring 4.0, which defines Bean information through Java code instead of XML files. Use the @Configuration annotation in the Java configuration class to mark this class as a configuration class, and then use the @Bean annotation to mark the Bean that needs to be managed by the Spring container.

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        MyBean myBean = new MyBean();
        myBean.setName("John");
        return myBean;
    }
}

Advantages: Java configuration classes are more concise than XML configuration files, and Java codes can be used to express Bean information, which improves readability and maintainability.

Disadvantages: The Java configuration class needs to be written manually. The writing process requires a certain basic knowledge of Java, and requires more time and energy.

Annotation-based configuration

Annotation-based configuration is a combination of automated scanning and annotations. In this way, we can use specific annotations to specify the information of a Bean, such as using @Value to inject property values, and @Autowired to inject dependencies. This method is more flexible than pure automatic scanning, and can be customized according to the actual situation.

@Component
public class MyBean {
    @Value("John")
    private String name;
    // 省略 getter/setter 方法
}

@Configuration
public class AppConfig {
    // 在配置类中定义需要注入的 Bean
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

// 在需要使用 MyBean 的地方注入即可
@Autowired
private MyBean myBean;

Advantages: Annotation-based configuration is more concise than XML configuration files and Java configuration classes. Bean information can be defined through annotations, which improves readability and maintainability.

 

Disadvantages: Annotation-based configuration may have the problem of irregular use of annotations or forgetting annotations, resulting in failure to inject, and additional testing and debugging work is required.

JavaEE annotations

JavaEE annotations are annotations defined in the JavaEE specification, and Spring supports the use of these annotations to define Bean information. For example, you can use @Resource to inject dependencies, @EJB to inject remote EJBs, and so on. This method is less used than other methods, but it is also a method that can be considered for projects using the JavaEE technology stack.

@Component
public class MyBean {
    @Resource(name = "myDependency")
    private MyDependency myDependency;
    // 省略 getter/setter 方法
}

// 在 Spring 配置文件中开启 JavaEE 注解支持
<context:annotation-config />

// 在需要注入 MyDependency 的地方定义 Bean
@Bean
public MyDependency myDependency() {
    return new MyDependency();
}

// 在需要使用 MyBean 的地方注入即可
@Autowired
private MyBean myBean;

Advantages: JavaEE annotations are annotations defined in the JavaEE specification, which are normative and universal.

Disadvantages: JavaEE annotations are not part of the Spring core, and additional configuration and integration work is required to use them.

 

By implementing the BeanFactoryPostProcessor interface

BeanFactoryPostProcessor is one of the extension point interfaces provided by the Spring container, which can be used to modify the properties and behavior of the Bean after the Bean is loaded. The Bean can be put into the Spring container after the Bean is loaded by implementing the BeanFactoryPostProcessor interface.

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 创建 BeanDefinition 并将其加入到 BeanFactory 中
        BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(MyBean.class)
            .addPropertyValue("name", "John")
            .getBeanDefinition();
        beanFactory.registerBeanDefinition("myBean", beanDefinition);
    }
}

// 在需要使用 MyBean 的地方注入即可
@Autowired
private MyBean myBean;

Advantages: By implementing the BeanFactoryPostProcessor interface, the properties and behavior of the Bean can be modified very flexibly, making the management of the Bean more convenient.

Disadvantages: You need to understand the life cycle and extension point mechanism of the Spring container, and you need to manually write the implementation code of BeanFactoryPostProcessor, which may be difficult for beginners.

 

Summarize

There are many ways to put beans into the Spring container, each with its advantages and disadvantages. In actual projects, it is necessary to select and configure according to the actual situation in order to achieve the optimal effect. In general, automatic scanning and annotation-based configuration are relatively common methods, and Java configuration classes are also a good choice, while XML configuration files and JavaEE annotations are relatively less commonly used. If you need more detailed management and configuration of Bean, you can consider implementing the BeanFactoryPostProcessor interface.

 

Guess you like

Origin blog.csdn.net/Dark_orange/article/details/129996552