Spring:确保首先初始化特定的bean [英] Spring: Make sure a particular bean gets initialized first

查看:181
本文介绍了Spring:确保首先初始化特定的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个库,用于运行时设置和配置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?

推荐答案

您的选择是:


  1. 使用 @DependsOn 注释(在春季3.0.x之后可用)或 依赖 xml-attribute并使所有使用配置记录器的类依赖于记录器工厂

  2. 使工厂成为记录器的实际工厂,并将记录器注入bean而不是直接调用工厂 - 这与选项1基本相同,除非隐含依赖关系。这是我推荐的选项。

  3. 将初始化代码移动到指定调用顺序的代码的一部分 - main()方法,或者在初始化Spring之前注册的 ServletContextListener

  1. Use @DependsOn annotation(available after spring 3.0.x) or depends-on xml-attribute and make all classes that use the configured loggers depend on the logger factory
  2. 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.
  3. Move the initialisation code to a part of your code where call order is specified – the main() method, or a ServletContextListener 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆