一般情况下,我们直接在@Component标注的类(Bean)下就能直接通过@Autowired、@Resource直接实现自动注入获取到Bean的实例,如下:
@Service
@Transactional(readOnly = true)
public class MyReadServiceImpl {@Resourceprivate MyReadMapper myReadMapper;
}
但是在工具类中,我们需要获取Bean的实例,那该怎么办呢?
要使用
@Resource或其他任何依赖注入注解(如@Autowired),目标对象本身必须是Spring容器管理的Bean。
所幸Spring框架中提供了一个接口——ApplicationContextAware,我们可以先通过这个接口获取到一个ApplicationContext实例context,再通过context.getBean(beanName)就能在无法使用依赖注入的类中获取到Bean的实例。
先声明一个类实现ApplicationContextAware接口,重写setApplicationContext给静态变量context赋值:
当一个类实现了这个接口时,Spring 容器在初始化该类的 Bean 实例后,会自动调用其
setApplicationContext(ApplicationContext applicationContext)方法,将当前ApplicationContext的引用注入到该类中。
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class MyBeanUtil implements ApplicationContextAware {public static ApplicationContext context = null;@Overridepublic synchronized void setApplicationContext(ApplicationContext context) {context = context;}}
接着就能在非Spring组件的工具类中通过ApplicationContext的实例使用Bean了,如下:
@Data
@Configuration
public class YmlConfig {@Value("${redis.pass}")private String redisIp;
}
public class MyUtil {private static final YmlConfig ymlConfig = SpringUtils.context.getBean(YmlConfig.class);
}