# Spring context tool class SpringContextUtils tool class

Spring context tool class SpringContextUtils tool class

problem analysis

Obtain the assembled Bean from the Spring context to facilitate the configuration of resource information in the configuration file. When a class implements ApplicationContextAware, this class can easily obtain all the Beans in the ApplicationContext. Application is initialized in the implementation class of ApplicationContextAware, so implementing this class can get all Beans in the current context.

Tool class implementation
@Component
public class SpringContextUtils  implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext = null;

    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        if(Objects.isNull(SpringContextUtils.applicationContext)){
    
    
            logger.info("=====>ApplicationUtils初始化...");
            SpringContextUtils.applicationContext = applicationContext;
        }
        if(Objects.nonNull(SpringContextUtils.applicationContext)){
    
    
            logger.info("=====>ApplicationUtils初始化成功!");
        }
    }

    /**
     * 获得当前的ApplicationContext
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[]'
     * @return org.springframework.context.ApplicationContext
     */
    public static ApplicationContext getApplicationContext(){
    
    
        return applicationContext;
    }

    /**
     * 根据名称拿到Bean
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[name]'
     * @return java.lang.Object
     */
    public static Object getBean(String name){
    
    
        return getApplicationContext().getBean(name);
    }

    /**
     * 从ApplicationContext中获得Bean并且转型
     *
     * @author LiDong
     * @date 2020/11/20
     * @param '[tClass]'
     * @return T
     */
    public static <T> T getBean(Class<T> tClass){
    
    
        return getApplicationContext().getBean(tClass);
    }
}
Test example
@RequestMapping("/test4")
public void test4(){
    
    
    try {
    
    
        RedissonClient redissonClient = (RedissonClient) SpringContextUtils.getBean("redissonClient");
        redissonClient.getSet("two").add("two");
    }catch (Exception e){
    
    
        logger.error(e.getMessage(),e);
    }
}

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/109861854