Reputation: 197
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?
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).
Upvotes: 4
Views: 16410
Reputation: 2896
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);
}
}
Upvotes: 5
Reputation: 279990
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
.
Upvotes: 9