Spring注入依赖分为三种,具体如下介绍:
1、构造函数注入
基于构造函数的注入依赖通过调用带参数的构造器实现,每个参数代表着一个依赖。示例如下:
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
上述类文件的构造器有两个参数,那么基于XML的配置文件如下所示:
<beans>
<bean name="foo" class="x.y.Foo">
<constructor-arg>
<bean class="x.y.Bar"/>
</constructor-arg>
<constructor-arg>
<bean class="x.y.Baz"/>
</constructor-arg>
</bean>
</beans>
如果构造器中使用简单的数据类型,那么配置文件中如何进行类型匹配呢,且看下面的示例:
package examples;
public class ExampleBean {
// No. of years to the calculate the Ultimate Answer
private int years;
// The Answer to Life, the Universe, and Everything
private String ultimateAnswer;
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
则配置文件如下:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
或者通过索引:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>
注意index是从0开始的。2、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...
}
MovieFinder对象就是通过setter方式注入的。
3、接口注入
此种方式使用较少,在此不作介绍。