使用ApplicationContextHolder 工具类 在spring容器中获取bean

新建ApplicationContextHolder 工具类

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

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }

 
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

 
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

 
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}

使用方式

不能通过autowire的方式引用redisTemplate是使用该工具类工具类

	private RedisTemplate redisTemplate;

	private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }


public void test(){
 RedisTemplate redisTemplate = getRedisTemplate();
	String value=redisTemplate.opsForValue().get("testk1");
	System.out.println(value);
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐