配置类中的 getBeansOfType
我的春季课程有问题。我需要获取 Configuration 类中某个类型的所有 Bean,以便将它们提供给另一个类。
现在的问题是,我不能这样做,除非我启动一个 ApplicationContext
但这不起作用,因为我调用的 Config 类使用我调用的配置类,所以我得到一个无限循环...
例如:
@Configuration
@Import(Calling.class)
public class MyConfig{
@Bean
public ExampleClass aBean(){
...
return aObject;
}
}
@Configuration
@Import(MyConfig.class)
public class Calling{
@Bean
public Foo anotherBean(){
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(myConfig.class);
ctx.getBeansOfType(ExampleClass.class);
return aObject;
}
}
我可以使用任何功能或模式来获取这些 Bean 吗?
I have a problem with my Spring Classes. I need to get all Beans of a type inside a Configuration class to give them to a another class.
The Problem now is, that I cant do that unless I startup a ApplicationContext
but that doesn't work, because the Config class I call up uses the config class I'm calling from, so I get a endless loop...
as example:
@Configuration
@Import(Calling.class)
public class MyConfig{
@Bean
public ExampleClass aBean(){
...
return aObject;
}
}
@Configuration
@Import(MyConfig.class)
public class Calling{
@Bean
public Foo anotherBean(){
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(myConfig.class);
ctx.getBeansOfType(ExampleClass.class);
return aObject;
}
}
Is there any functionality or pattern I can use to get these Beans?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用@Configuration,您需要非常小心,不要从上下文中“拉”bean,因为您经常会遇到这些无限循环。
试试这个:
这种声明性方法应该有望解决无限循环问题。
另请注意,您应该避免循环
@Import
。仅朝一个方向执行此操作,如上例所示。With
@Configuration
, you need to be very careful not to "pull" beans from the context, since you often get these infinite loops.Try this instead:
This declarative approach should hopefully get around the infinite loop problem.
Note also, you should avoid cyclic
@Import
. Do it in one direction only, as in the above example.您可以使用 LazyInitTargetSource 除非必须在上下文初始化时在两个 bean 上调用方法
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/aop/target/LazyInitTargetSource.html
(否则最好删除循环依赖(如果可能)
you could use LazyInitTargetSource unless method(s) must be called on both beans on context initialization
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/aop/target/LazyInitTargetSource.html
(otherwise it'd be best to remove the circular dependency if possible)