我们在SpringBoot中使用Bean的方式是@Autowired 方式自动注入的,但是在某些普通类中使用Bean的话,就不能使用这种方式,比如以下场景:
在使用 import org.java_websocket.client.WebSocketClient; 作为客户端去链接WebSocket服务器的时候,必须使用有参构造,而不能自动注入的情况下,我们要在WebSocketClient中使用自动注入过的redis、mysql等,使用 @Autowired 获取的对象是null,那么只能直接从SpringBoot的Bean对象管理器中拿取所需要的Bean对象。
操作步骤:
一、定义一个获取Bean的工具类。
定义工具类 SpringUtil (名字自定义) 实现 org.springframework.context.ApplicationContextAware 这个接口,代码如下:
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
public static <T> T getBean(String beanName, Class<T> beanClass) {
return applicationContext.getBean(beanName, beanClass);
}
}
记住,这个类一定要添加 @Component 组件注解
二、使用demo
在一个普通类中使用,比如我们想获取RabbitMq的自动注入对象。
RabbitTemplate rabbitTemplate= SpringUtil.getBean(RabbitTemplate.class);
rabbitTemplate.convertAndSend("test_message","test"+new Date());
原理:就是SpringBoot的Bean都交由ApplicationContext applicationContext 来管理,我们只是间接的从 ApplicationContext applicationContext 这个对象中获取,更多的可以参考Spring的原理。