简体   繁体   中英

Does Spring Java Configuration bean method calls get injected with managed beans at runtime?

Consider the following code:

public class AImpl implements A {}

public class BImpl implements B {
    private final A a;

    public B(A a){
        this.a = a;
    }
}

@Configuration
public class MyConfiguration {
    @Bean
    public A bean1(){
        return new AImpl(); 
    }

    @Bean 
    public B bean2() {
        return new BImpl(bean1());
    }

    @Bean
    public B bean3() {
        return new BImpl(bean1());
    }
}

Would the reference that bean2 and bean3 have to bean1 be a spring managed singleton or a new instance? Ie does spring intercept method calls in a Java configuration class with proxies to the proper application context?

Update from my understanding, CGLIB library is involved in java configuration classes to modify bytecode, does this mean the latter scenario is true? I just haven't quite wrapped my head around how it works yet.

Class A Should be represented in both bean2 and bean2 by this same object around this same ApplicationContext (especially if you declaring Beans as methods in @Configuration ), but you can use also Dependency Injections implemented in Spring Container. This code in my opinion is more clear and unequivocal, but reader must know how Autoriwiring works.

This code is equivalently:

@Configuration
    public class MyConfiguration {
    @Bean
    public A bean1(){
        return new AImpl(); 
    }

    @Bean 
    public B bean2(A bean1) {
        return new BImpl(bean1);
    }

    @Bean
    public B bean3(A bean1) {
        return new BImpl(bean1);
    }
}

Second way:

Add @Component and @Inject/@Autowired on declared classes (you can't do this in legacy code, without AOP).

@Component
public class AImpl implements A {}

@Component
public class BImpl implements B {
    private final A a;

    @Inject
    public B(A a){
        this.a = a;
    }
}

But this solution need to add @ComponentScan(packages="name.of.your.package") to your @Configuration class.

@ComponentScan(packages="name.of.your.package")
@Configuration
public class MyConfiguration {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM