通过ApplicationContextAware来获得ApplicationContext,然后获取相关Bean进行操作
举例说明
@Configuration
public class CommonConfig implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 获取RabbitTemplate
RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
// 设置ReturnCallback
rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
// 投递失败,记录日志
log.info("消息发送失败,应答码{},原因{},交换机{},路由键{},消息{}",
replyCode, replyText, exchange, routingKey, message.toString());
// 如果有业务需要,可以重发消息
});
}
}
例子二
/**
* 将容器缓存到本地
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
// 容器对象
private static ApplicationContext applicationContext = null;
private SpringContextHolder() {
}
/**
* 获取容器中的Bean对象
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
}
标签:applicationContext,SpringBoot,ApplicationContext,容器,getBean,Bean,IOC,public
From: https://www.cnblogs.com/jintaocode/p/17598102.html