1.
Autowired可以将@Autowired注解为传统的setter方法,也可以用于构造器或成员变量在默认的情况下,如果找不到合适的bean将会导致aotowired失败或者是抛出异常, 但是可以通过下面的代码来避免。
public class SimpleMovieLister{
private MovieFinder movieFinder;
@Autowired(required=flase)
public void setMovieFinder(MovieFinder movie){
this.movieFinder = movie;
}
}
每个类中只能有一个构造器被表示为required = true
在spring的官方文档中如果是必要的属性,建议使用@required注解
2.
通过@Autowired的注解可以使用list集合或者是map集合来输出或者是使用这个类中的资源。
public interface BeanInterface {
//定义的一个接口
}
@Order(2)//可以更改排序的位置
@Component
public class One_interface implements BeanInterface{
//实现接口的一个类
}
@Order(1)
@Component
public class Two_interface implements BeanInterface{
//实现接口的一个类
}
@Component
public class BeanInvoker {
@Autowired
private List<BeanInterface> list;
public void say(){
if(list != null && list.size() != 0)
for (BeanInterface beanInterface : list) {
System.out.println(beanInterface.getClass().getName());
}
else
System.out.println("not null");
}
}
@RunWith(BlockJUnit4ClassRunner.class)
public class TestInterface {
public TestInterface() {}
@Test
public void say(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-interface.xml");
BeanInvoker beaninvoker = ctx.getBean("beanInvoker", BeanInvoker.class);
beaninvoker.say();
}
}
//最后就是xml文档的配置
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--这个是在这个包里面查找bean-->
<context:component-scan base-package="spring_test06"></context:component-scan>
</beans>