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

前端 未结 2 1773
南笙
南笙 2020-12-19 15:58

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

相关标签:
2条回答
  • 2020-12-19 16:20

    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

    public class A {
    
        @Autowired
        private class B b;
    
        public A{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 
        }
    
    }
    
    0 讨论(0)
  • 2020-12-19 16:22

    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.

    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.

    0 讨论(0)
提交回复
热议问题