Spring依赖注入模式

Spring依赖注入方式

Spring注入方式有三种:

1.接口注入(不常用)

2.构造器注入

3.setter注入

 

构造方法注入:

public class UserService {
                     public UserService(UserDAO userDAO) {
                    super();
                    this.userDAO = userDAO;
           }
}

<bean id="userDao" class="com.bjsxt.dao.impl.UserDAOImpl">

<bean id="userService" class="com.bjsxt.service.UserService">
    <constructor-arg>
            <ref bean="userDao"/>
    </constructor-arg>
 </bean>

 

setter方法注入:

public class UserService {
          private UserDAO userDAO;  
          public UserDAO getUserDAO() {
                    return userDAO;
          }
          public void setUserDAO(UserDAO userDAO) {
                   this.userDAO = userDAO;
          }
 
}

 <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"></bean>
 <bean id="userService" class="com.bjsxt.service.UserService">
            <property name="userDAO" ref="u" />
 </bean>

 

 

1.使用构造器方式注入

private PersonDaoBean personDaoBean;

private String name;

private int id;

 

public PersonServiceBeanImpl(PersonDaoBean personDaoBean, String name,

int id) {

this.personDaoBean = personDaoBean;

this.name = name;

this.id = id;

}

<bean id="personService" class="com.zhen.service.impl.PersonServiceBeanImpl">

<constructor-arg index="0" type="com.zhen.dao.PersonDaoBean" ref="personDaoBean"/>

<constructor-arg index="1">

<value>chenzhen</value>

</constructor-arg>

<constructor-arg index="2" value="110"/>

</bean>