注入类型分为三种: 

a)     setter(常用)

package com.bebig.service;

import com.bebig.dao.UserDAO;
import com.bebig.model.User;

//逻辑业务层
public class UserService {
    
private UserDAO userDAO;

    
public void add(User u) {
        userDAO.save(u);

    }


    
public void setUserDAO(UserDAO userDAO) {
        
this.userDAO = userDAO;
    }


    
public UserDAO getUserDAO() {
        
return userDAO;
    }

}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation
="
http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>

    
<!-- a service object; we will be profiling its methods -->
    
<bean id="u" class="com.bebig.dao.impl.UserDAOImpl" />
    
<bean id="userService" class="com.bebig.service.UserService">
    
<!-- 通过userDAO的setter方法将u注入 -->
        
<property name="userDAO" ref="u" />
    
</bean>

</beans>


b)     构造方法(少用)

package com.bebig.service;

import com.bebig.dao.UserDAO;
import com.bebig.model.User;
//逻辑业务层
public class UserService {
    
//构造函数里有一个userDAO对象需要初始化
    public UserService(UserDAO userDAO) {
        
super();
        
this.userDAO = userDAO;
    }


    
private UserDAO userDAO;

    
public void add(User u) {
        userDAO.save(u);

    }


    
public void setUserDAO(UserDAO userDAO) {
        
this.userDAO = userDAO;
    }


    
public UserDAO getUserDAO() {
        
return userDAO;
    }

}

beans.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation
="
http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>

    
<!-- a service object; we will be profiling its methods -->
    
<bean id="u" class="com.bebig.dao.impl.UserDAOImpl" />
    
<bean id="userService" class="com.bebig.service.UserService">
    
<!-- 构造函数指定注入bean -->
        
<constructor-arg>
            
<ref bean="u" />
        
</constructor-arg>
    
</bean>

</beans>


c)     接口注入(少用)