一,在方法参数中使用@Qualifier
在创建A对象时,需要用到B对象,可以在方法的参数中使用@Qualifier("beanName")的方式注入;
注意:beanName 必须指定,且两个必须一致,否则编译不通过
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class MyConfig {
@Bean
public A getA(@Qualifier("b") B b){
A a = new A();
System.out.println("getA方法中的b="+b);
a.setB(b);
return a;
}
@Bean("b")
public B getB(){
B b =new B();
System.out.println("getB方法中的b="+b);
return b;
}
}
可以看到两个B对象的内存地址一样
二,直接调用的方式
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class MyConfig {
@Bean
public A getA(){
A a = new A();
B b =getB();//直接调用得到对象
System.out.println("getA方法中的b="+b);
a.setB(b);
return a;
}
@Bean("b")
public B getB(){
B b =new B();
System.out.println("getB方法中的b="+b);
return b;
}
}
这种方式我一直以为会产生两个B对象,但实际上spring做了处理,只会产生一个对象,结果如下:
这是为啥呢?
这就说到了@Configuration配置类的full和lite模式,具体看@Configuration配置类的full和lite模式_不惧不惑的博客-优快云博客_full模式
三,定义成员变量进行注入
把B定义成了一个成员变量,使用@Resource给其注入值(@Autowired也可以)
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class MyConfig {
@Resource
private B b;
@Bean
public A getA(){
A a = new A();
System.out.println("成员变量中的b="+b);
a.setB(b);
return a;
}
@Bean("b")
public B getB(){
B b =new B();
System.out.println("getB方法中的b="+b);
return b;
}
}
总结:
方式一、方式三都可以跨类使用,方式二只适合本类中使用