@Bean
修饰需要传参数的方法:
参数是类
@Configuration
public class PersonConfig {
@Bean
public Dep getDep(Stu stu){
System.out.println(stu);
Dep dep = new Dep();
dep.setStu(stu);
return dep;
}
}
需要注册spring容器的类Dep:
public class Dep {
public String depName;
public Stu stu;
public String getDepName() { return depName; }
public void setDepName(String depName) { this.depName = depName; }
public Stu getStu() { return stu; }
public void setStu(Stu stu) { this.stu = stu; }
}
注入接口Stu和实现类Stu1:
@Component
public interface Stu {
}
@Component
public class Stu1 implements Stu {
}
调用:
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"applicationContext.xml"});
Dep dep = (Dep) context.getBean("getDep");
}
}
运行结果:
com.ymqx.pojo.Stu1@7c6908d7
结果可见,默认使用接口 Stu 的实现类Stu1。
如果再声明一个实现类Stu2:
@Component
public class Stu2 implements Stu {
}
运行报错:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getDep' defined in class path resource [com/ymqx/config/PersonConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.ymqx.pojo.Stu]: : No unique bean of type [com.ymqx.pojo.Stu] is defined: expected single matching bean but found 2: [stu1, stu2]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.ymqx.pojo.Stu] is defined: expected single matching bean but found 2: [stu1, stu2]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:730)
因为Stu用两个实现类,spring不知道注入哪个。
只需要将形参名称修改为想要注入的类名即可。
@Configuration
public class PersonConfig {
@Bean
public Dep getDep(Stu stu2){
System.out.println(stu2);
Dep dep = new Dep();
dep.setStu(stu2);
return dep;
}
}
运行结果:
com.ymqx.pojo.Stu2@4b2bac3f
综上所述,如果 Spring 容器中只有一个 Dep 类型的 bean,则默认按照类型匹配注入 Dep 的 bean。如果有多个 Dep 类型的 bean,则按照名称(此处应为 stu2)匹配注入对应的bean。
参数是List
@Configuration
public class PersonConfig {
/**
* 此处将把所有实现Stu接口的类的Bean注入list集合中
*/
@Bean
public Dep getDep(List<Stu> stuList){
System.out.println(stuList);
Dep dep = new Dep();
dep.setStuList(stuList);
return dep;
}
}
运行结果:
[com.ymqx.pojo.Stu1@5e5d171f, com.ymqx.pojo.Stu2@24313fcc]
参数是List类型时,将把所有实现Stu接口的类的Bean注入list集合中。