Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Spring管理的web应用程序中,在Log4J Appender中检索Spring管理的bean有哪些可用选项?_Spring_Log4j_Javabeans_Appender - Fatal编程技术网

在Spring管理的web应用程序中,在Log4J Appender中检索Spring管理的bean有哪些可用选项?

在Spring管理的web应用程序中,在Log4J Appender中检索Spring管理的bean有哪些可用选项?,spring,log4j,javabeans,appender,Spring,Log4j,Javabeans,Appender,我目前的构建主管在理论上有一个很好的想法——构建一个定制的Log4J appender,它接受Spring管理的bean,并使用它们将错误记录到标准日志文件以外的各种其他源。然而,除了在启动时使用应用程序上下文创建一个初始化的单例(马上编写代码),我似乎想不出在Log4J appender中检索Spring管理的bean的任何其他选项 public class SpringSingleton implements ApplicationContextAware { private sta

我目前的构建主管在理论上有一个很好的想法——构建一个定制的Log4J appender,它接受Spring管理的bean,并使用它们将错误记录到标准日志文件以外的各种其他源。然而,除了在启动时使用应用程序上下文创建一个初始化的单例(马上编写代码),我似乎想不出在Log4J appender中检索Spring管理的bean的任何其他选项

public class SpringSingleton implements ApplicationContextAware {
    private static ApplicationContext context;
    public SpringSingleton() {
        super();
    }
    public static ApplicationContext getContext() {
        return SpringSingleton.context;
    }
    public void setApplicationContext(ApplicationContext context) {
        if(SpringSingleton.context != null) {
            throw new IllegalStateException("Context is already set!");
        }
        SpringSingleton.context = context;
    }
}

理想情况下,这些属性可以像Spring中的bean一样通过依赖项注入进行设置——bean引用永远不会改变,不管初始化了多少个appender。有什么想法吗?

您将遇到一个boostrap问题,因为log4j必须在Spring之前初始化。无论您使用的是a还是Log4j的标准初始值设定项,它都必须在应用程序上下文启动之前启动

现在,从理论上讲,您可以让您的自定义appender“懒洋洋地”初始化它们自己(通过您上面建议的方法或者让appender自己“半”单例—例如,appender类有一个静态实例字段,该字段由
afterPropertiesSet()填充)
method;这样您就可以在Spring中将appender本身创建为bean),但它看起来有些混乱和不一致


另一种方法是在初始化Spring上下文后动态重新配置Log4j;e、 g.编写一个捕获
ContextStartedEvent
,从上下文中获取
Appender
类型的所有bean,并将它们添加到Log4j配置中。这也允许您将appender创建为bean,但在某种程度上避免了单例混乱。

有点晚,但我希望这可以帮助其他人。我在以下链接中提供的答案中记录了此问题的解决方案:


哦……我喜欢听的人的想法。我把它传过去。不过,我会等待更多的答案,因为你们似乎并没有对rep造成太大的伤害:)+1.嘿,嘿-引用《辛普森一家》(Simpsons)中的Rich Texan()“我一直在努力争取这个rep”:-)好东西。显然,我们已经有了一个BeanFactoryPostProcessor实现,它确实允许设置额外的appenders数组,因此我们将使用它,但由于没有人回答这个问题,而且这肯定是合适的,因此您可以获得更多的rep:)