Additional solution:
MyServiceApplicationContext.java:
@Service
public class MyServiceApplicationContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
MyCustomAppender.java:
@Plugin(name = "MyCustomAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
public class MyCustomAppender extends AbstractAppender {
private MyBean myBean;
protected MyCustomAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties);
}
@PluginFactory
public static MyCustomAppender createAppender(
@PluginAttribute("name") String name,
@PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
@PluginElement("Layout") Layout layout,
@PluginElement("Filters") Filter filter,
@PluginElement("Properties") Property[] properties) {
return new MyCustomAppender(name, filter, layout, ignoreExceptions, properties);
}
@Override
public void append(LogEvent event) {
if (myBean == null) {
// the appender is called before spring initialization
ApplicationContext context = MyServiceApplicationContext.getApplicationContext();
if (context != null) {
myBean = context.getBean(MyBean.class);
}
}
if (myBean != null) {
myBean.doSomething();
}
}