1.使用
2.数组及Map的自动注入:
package com.wuyonghu.autowired; public interface BeanInterface { } package com.wuyonghu.autowired; import org.springframework.stereotype.Component; @Component public class BeanImpl1 implements BeanInterface{ } package com.wuyonghu.autowired; import org.springframework.stereotype.Component; @Component public class BeanImpl2 implements BeanInterface{ } package com.wuyonghu.autowired; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BeanInvoker { @Autowired private List<BeanInterface> list; public void say(){ if(null!=list){ for (BeanInterface bean : list) { System.out.println(bean.getClass().getName()); } }else{ System.out.println("自动注入失败"); } } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="com.wuyonghu" /> </beans>测试代码:
@Test public void testHello7() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); BeanInvoker resources = (BeanInvoker) context.getBean("beanInvoker"); resources.say(); }