Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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).

like image 698
DashingSuprHero Avatar asked Dec 12 '22 05:12

DashingSuprHero


2 Answers

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.

like image 118
Sotirios Delimanolis Avatar answered Jan 26 '23 01:01

Sotirios Delimanolis


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); 
    }

}
like image 28
Peter Jurkovic Avatar answered Jan 26 '23 01:01

Peter Jurkovic