spring中的依赖注入一般以set/get方法为多,但有些情况下需要构造器注入,也就是类构造器有参数的情况下 ,以下为一个demo
一 类文件代码
package chainofresponsibility;
/**
* 处理不大于Trouble里面存放数字的类
* @author fengyue
*
*/
public class LimitProcessor extends Processor {
private Integer limit;
private LimitProcessor(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public LimitProcessor(String name,Integer limit) {
this(name);
this.limit=limit;
// TODO Auto-generated constructor stub
}
/**
* 如果Trouble里面存放数字不大于limit则为可以处理
*/
protected boolean isCanProcess(Trouble t) {
return t.getNumber().compareTo(limit)!=1;
}
protected ProcessResult resolve(Trouble t) {
return new ProcessResult(true,getSuccessMess(t));
}
}
2对应Spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="limitPro" class="chainofresponsibility.LimitProcessor">
<constructor-arg type="java.lang.String" value="LimitProcessor">
</constructor-arg>
<constructor-arg type="java.lang.Integer" value="26">
</constructor-arg>
</bean>
</beans>