解决无法注入spring容器,获取不到spring容器中的bean问题
前两天工作中遇到一个问题,收到的需求是根据logbak日志实现通过过滤错误日志发送预警邮件到邮箱,logback自定义实现类如下
/**
* @author KyleYao
* @date 2020/4/21 13:01
* @description: 错误日志邮件发送
*/
@Componet
public class ErrorEmailAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private final String[] TO = {"2854646670@qq.com"};
private final String SUBJECT_PREFIX = "【Error】: ";
@Autowired
private MailUtils mailUtils;
@Override
protected void append(ILoggingEvent event) {
// System.out.println("level =" + event.getLevel());
// System.out.println("msg =" + event.getMessage());
// System.out.println("level =" + event.getLevel());
//根据规则做相应调用 TODO
if (event.getMessage().contains("邮件")) {
System.out.println("开始发送邮件");
MailBean mailBean = getMailBean(event);
MailUtils.getInstance().sendMailAttachment(mailBean);
}
}
private MailBean getMailBean(ILoggingEvent event) {
MailBean mailBean = new MailBean();
mailBean.setTo(TO);
mailBean.setSubject(SUBJECT_PREFIX + event.getLoggerName());
mailBean.setContent("date = " + event.getTimeStamp() + "\n" +
"level =" + event.getLevel() + "\n" +
"message =" + event.getMessage() + "\n" +
"thread = " + event.getThreadName() + "\n" +
"logger =" + event.getLoggerName() + "\n" +
"message =" + event.getMessage());
return mailBean;
}
}
因为MailUtils是通过@Service注解注入到spring容器中的,所以我这里给这个类加上@Componet注解想让他加入到容器中,这样可以获取自动注入的MailUtils,但是发现怎么也获取不到(这个原因后续研究),后来在同事帮助下使用了另一种写法,改造了一下MailUtils
@Slf4j
@Service
public class MailUtils {
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private MailProperties mailProperties;
public static MailUtils getInstance() {
return SpringContextUtils.getBean(MailUtils.class);
}
截取部分,通过自己封装的spring上下文工具获取到他的实体,这样在某些类无法注入到容器中时又想获得spring容器中的管理的bean的时候可以通过这种方式实现。
附:spring上下文工具如下:
/**
* Spring上下文工具类
*
* @author Andrew
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextUtils.applicationContext == null) {
SpringContextUtils.applicationContext = applicationContext;
}
}
public static ApplicationContext getContext() {
return SpringContextUtils.applicationContext;
}
public static <T> T getBean(Class<T> beanType) {
return applicationContext.getBean(beanType);
}
public static <T> T getBean(String beanName, Class<T> beanType) {
return applicationContext.getBean(beanName, beanType);
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static ParamsProperties getParamsProperties() {
return (ParamsProperties) getBean("paramsProperties");
}
}