Java Spring 如何在不使用 @Component 或其他派生类的情况下自动装配组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24373237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring How to autowire a component without using @Component or other derivatives
提问by DashingSuprHero
I would like to autowire a component (still using the @Autowired annotation), but not require it to have the @Component (or other similar annotations) on it. How would I do this?
我想自动装配一个组件(仍然使用 @Autowired 注释),但不要求它有 @Component (或其他类似的注释)。我该怎么做?
public class A {
@Autowired
private class B b;
}
@Component
public class B {
}
This would be convenient in order to allow autowiring of class A without requiring the creation of A, unless we needed it (in otherwise on the fly by reflection using the class name).
为了允许自动装配类 A 而不需要创建 A,这将很方便,除非我们需要它(否则通过使用类名进行反射)。
采纳答案by Peter Jurkovic
I don't sure, If I correctly understood to your question. But if you want inject bean B
without marking bean A
via some annotation, or xml definition, you can use SpringBeanAutowiringSupport
我不确定,如果我正确理解你的问题。但是如果你想通过一些注解或者 xml 定义在B
不标记bean 的情况下注入 bean A
,你可以使用SpringBeanAutowiringSupport
public class A {
@Autowired
private class B b;
public A{
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
}
回答by Sotirios Delimanolis
Injection and autowiring do not require@Component
. They require beans. @Component
states that the annotated type should have a bean generated for it. You can define beans in other ways: with a <bean>
declaration in an XML context configuration, with a @Bean
method in a @Configuration
class, etc.
注入和自动装配不需要@Component
. 他们需要豆类。@Component
声明注释类型应该为它生成一个 bean。您可以通过其他方式定义 bean:<bean>
在 XML 上下文配置中使用声明,@Bean
在@Configuration
类中使用方法等。
Your last sentence doesn't make much sense. You can't process injection targets in a bean without creating a bean. You also can't inject a bean without creating it. (Applied to scopes, bean may refer to the target source/proxy and not the actual instance.) Perhaps you want @Lazy
.
你的最后一句话没有多大意义。您不能在不创建 bean 的情况下处理 bean 中的注入目标。您也不能在不创建 bean 的情况下注入它。(应用于作用域,bean 可能指的是目标源/代理,而不是实际实例。)也许您想要@Lazy
.