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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:50:35  来源:igfitidea点击:

Spring How to autowire a component without using @Component or other derivatives

javaspring

提问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 Bwithout marking bean Avia 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. @Componentstates 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 @Beanmethod in a @Configurationclass, 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.