6/13整理

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方法上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值