Spring三种常用的注入:setter注入,构造注入,注解注入
构造方法注入:
在类中,不用为属性设置setter方法,只需提供构造方法,在构造文件中配置该类bean,并配置构造器,在配置构造器中用。
//ApplicationContext.xml
<bean id="action" class="com.action.UserAction">
<constructor-arg index ="0" name="name" value="Murphy"></constructor-arg>
</bean>
提供构造方法
public class UserAction {
private String name;
public UserAction(String name) {
this.name = name;
}
setter注入:
完成setter方法注入是在容器调用无参构造方法后调用setter方法完成注入,官网示例:
public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on the MovieFinder
private MovieFinder movieFinder;
// a setter method so that the Spring container can inject a MovieFinder
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// business logic that actually uses the injected MovieFinder is omitted...
}
注解注入:
自动装配注解,@Autowired
@Autowired(required=true):当使用@Autowired注解的时候,其实默认就是@Autowired(required=true),表示注入的时候,该bean必须存在,否则就会注入失败
@Autowired(required=false):表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。
required属性含义和@Required一样,只是@Required只适用于基于XML配置的setter注入方式,只能打在setting方法上。