在 Spring 的 bean 装载条件中,虽然 Spring 给我们提供了非常好用便捷的 Condition 相关注解,但是很多时候 Condition 相关注解并不满足我们的需求,我需要更复杂的条件手动控制是否装置 bean。这个时候我们就可以实现 Spring 为我们提供的几个接口来实现手动 bean 的注入。
一、ApplicationContextAware 接口
在某些特殊的情况下,bean 需要实现某个功能,但该功能必须借助于 Spring 容器才能实现,此时就必须让该 bean 先获取 Spring 容器,然后借助于 Spring 容器实现该功能。为了让 bean 获取它所在的 Spring 容器,可以让该 bean 实现 ApplicationContextAware 接口。ApplicationContextAware 通过它 Spring 容器会自动把上下文环境对象调用ApplicationContextAware 接口中的 setApplicationContext 方法。在 ApplicationContextAware 的实现类中,就可以通过这个上下文环境对象得到 Spring 容器中的 bean。
@Component
public class MyContextAware implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("SpringWebSocketContextAware");
// 将 applicationContext 转换为 ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationC