3.3.1.1. Constructor Injection
Constructor-based DI is effected by invoking a constructor with a number of arguments, each representing a dependency. Additionally, calling a static
factory method with specific arguments
to construct the bean, can be considered almost equivalent, and the rest of this text will consider arguments to a constructor and arguments to a static
factory method similarly. Find below an example of a class that could only
be dependency injected using constructor injection. Notice that there is nothing special about this class.
public class SimpleMovieLister { // theSimpleMovieLister
has a dependency on aMovieFinder
private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' aMovieFinder
public SimpleMovieLister(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually 'uses' the injectedMovieFinder
is omitted... }
There is no potential for ambiguity here (assuming of course that Bar
and Baz
classes are not related in an inheritance hierarchy). Thus the following configuration will work just fine, and you do
not need to specify the constructor argument indexes and / or types explicitly.
<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>
When another bean is referenced, the type is known, and matching can occur (as was the case with the preceding example). When a simple type is used, such as<value>true<value>
, Spring cannot determine the type of the value, and so
cannot match by type without help. Consider the following class:
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; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- udaoimpl is a UserDAOImpl Object--> <bean id="udaoimpl" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <!-- userService is a UserService Object--> <bean id="userService" class="com.bjsxt.service.UserService"> <!-- 最常用的setter方法注入 --> <!--userService's setUserDAO method DI(注入) 之前产生的udaoimpl对象--> <!-- <property name="userDAO"><ref bean="udaoimpl"/></property> --> <!-- 不推荐,可以忘记‘’‘’ userService的构造方法注入 --> <constructor-arg> <ref bean="udaoimpl"/> </constructor-arg> <!--<property name="userDAO" ref="udaoimpl"/> --> </bean> </beans>
版权声明:本文为博主原创文章,未经博主允许不得转载。