问题描述
我有一个库进行运行时设置和 log4j 配置(没有 log4j.properties 或 log4j.xml).我已经定义了一个名为 MyLoggerFactory 的 bean,我希望它成为第一个使用 spring 初始化的 bean.我看到 spring 已经提交了一个问题来支持初始化顺序,但我想知道是否有办法将 bean 标记为 spring 容器要初始化的第一个 bean?
I have a library doing runtime setup and configuration of log4j (no log4j.properties or log4j.xml). I have defined a bean with class called MyLoggerFactory and I want this to be the first bean to be initialised using spring. I have seen that an issue has already been filed with spring to have support for order of initialisation but I was wondering whether there was a way to mark a bean as the first bean to be initialised by spring container?
推荐答案
您的选择是:
- 使用
@DependsOn
注解(spring 3.0.x 后可用)或depends-on
xml-attribute 并使所有使用配置记录器的类依赖于记录器工厂 - 使工厂成为记录器的实际工厂,并将记录器注入到 bean 中,而不是直接调用工厂——这与选项 1 基本相同,只是隐含了依赖关系.这是我推荐的选项.
- 将初始化代码移到指定调用顺序的代码部分 -
main()
方法,或在初始化 Spring 的方法之前注册的ServletContextListener
.
- Use
@DependsOn
annotation(available after spring 3.0.x) ordepends-on
xml-attribute and make all classes that use the configured loggers depend on the logger factory - Make the factory an actual factory for loggers, and inject the loggers into the beans instead of calling the factory directly – this is essentially the same as option 1, except the dependency is implied. This is the option I'd recommend.
- Move the initialisation code to a part of your code where call order is specified – the
main()
method, or aServletContextListener
registered before the one that initializes Spring.
在 Spring 中无法明确定义初始化顺序,而且可能永远不会——考虑到您可以加载许多可能具有冲突顺序的应用程序上下文配置文件,因此无法为其定义有用的语义.我还没有看到通过重构代码以更好地符合依赖项注入模式无法实现所需排序的情况.
There is no way to explicitly define initialisation order in Spring and likely never will be – there's no way to define useful semantics for it considering you can load many application context configuration files which might have conflicting orderings. I've yet to see a case where the desired ordering couldn't be achieved by refactoring your code to better conform to the dependency injection pattern.
这篇关于Spring:确保首先初始化特定的 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!