一、对集合类进行标注
1、一个实体类中声明一个带泛型的集合
2、给这个集体添加一个注解@Autowired
3、当spring容器启动时,给集合注入值起,会将spring容器中所有的bean(匹配泛型的类及其子类)的所有该集合的值
重点:基于Map的集合.key指的spring容器中bean的名称。value是spring中泛型的值
二、通过实例代表加以说明
假设有一个大型项目,spring容器中某个接口的所有实例类。这个时候我们就可以通过集合类标注的方法进行测试。
案例 :假设我们有一个ProductDao接口,针对不同的数据他有不同的实现类。现在我想知道spring容器内ProductDao的所有子类。
代码如下:
1、ProductDao
public interface ProductDao {
}
2、oracle的实现类ProductOracleDaoImpl
import org.springframework.stereotype.Repository;
@Repository
public class ProductOracleDaoImpl implements ProductDao{
}
3、Sybase的实现类
@Repository
public class ProductSybaseDaoImpl implements ProductDao{
}
注:实现类一定要加注解,确保该类被spring容器实例化
3、测试类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Container {
@Autowired
private List<ProductDao> products;
@Autowired
private Map<String,ProductDao> ps;
@Test
public void test01(){
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring.xml");
Container container=(Container)ac.getBean("container");
System.out.println(container.products);
System.out.println(container.ps);
System.out.println(container.ps.get("productOracleDaoImpl"));
}
输出结果:
[spring.ioc.demo3.ProductOracleDaoImpl@9b6220, spring.ioc.demo3.ProductSybaseDaoImpl@1474e45]
{productOracleDaoImpl=spring.ioc.demo3.ProductOracleDaoImpl@9b6220, productSybaseDaoImpl=spring.ioc.demo3.ProductSybaseDaoImpl@1474e45}
spring.ioc.demo3.ProductOracleDaoImpl@9b6220