Implement the ApplicationContextAware interface to get all bean objects and property values

0. Problem background

In web programs, spring is usually used to manage all instances (beans), and sometimes in order to use the instantiated beans in the program, such code is usually used:

ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-common.xml");  
AbcService abcService = (AbcService)appContext.getBean("abcService");  

But there is a problem with this: because it reloads applicationContext-common.xmland instantiates the context bean, if some thread configuration classes are also in this configuration file, it will cause the thread doing the same work to be started twice. Once when the web container is initialized, and once when it is instantiated as shown by the code above. It's like re-initializing it again! ! ! ! This creates redundancy.

1. Solution

When a class implements this interface (ApplicationContextAware), this class can easily obtain all the beans in the ApplicationContext . In other words, this class can directly obtain all referenced bean objects in the spring configuration file. At the same time, the corresponding value is obtained according to the "key".

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
public final class SpringUtils implements ApplicationContextAware {

    /**
    *上下文对象
    */
    @Getter
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    public static Object getBean(String name) {
        return SpringUtils.applicationContext.getBean(name);
    }

    public static String getProperty(String key) {
        //获取配置文件对象,根据key获取值
        return SpringUtils.applicationContext.getEnvironment().getProperty(key);
    }
}

Guess you like

Origin blog.csdn.net/qq_35207086/article/details/124272878