我正在创建一个java spring boot应用程序,我需要将(信息日志)记录到特定的数据库表中。为此,我创建了一个扩展 AppenderBase 类的自定义附加程序类。现在的问题是,在我的自定义附加程序类中,我想使用 spring 的 application.properties 文件中提供的数据库属性创建/访问 jdbctemplate 对象。
如何在自定义附加程序中访问 spring 的 jdbctemplate 对象?
这是代码示例 -
public class MyDBAppender extends AppenderBase<ILoggingEvent> {
private JdbcTemplate jdbcTemplate;
@Override
protected void append(ILoggingEvent eventObject) {
jdbcTemplate.savelog(....);
}
}
最佳答案
您可以通过在类级别添加 @Component
注释来创建 MyDBAppender 的 Spring Bean。
或者,如果您不想这样做或者这不起作用,您可以创建一个辅助类来访问 ApplicationContext:
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
public static <T> T getBean(Class<T> beanType) {
return context.getBean(beanType);
}
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
context = ac;
}
}
访问JdbcTemplate的用法是这样的。
JdbcTemplate jdbcTemplate = ApplicationContextProvider.getBean(JdbcTemplate.class);
关于java - 用于 Spring Boot 应用程序的 Logback 自定义数据库附加程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56537643/