Spring:确保首先初始化特定的bean [英] Spring: Make sure a particular bean gets initialized first
问题描述
我有一个库,用于运行时设置和配置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
注释(在春季3.0.x之后可用)或依赖
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!