UserService.java
package com.bebig.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

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

public class UserService {
    
private UserDAO userDAO;

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

    }


    @Autowired
    
// 自动装配
    
// @Qualifier指定要注入的对象名
    public void setUserDAO(@Qualifier("u") UserDAO userDAO) {
        
this.userDAO = userDAO;
    }


    
public UserDAO getUserDAO() {
        
return userDAO;
    }


    
public void init() {
        System.out.println(
"init.");
    }


    
public void destory() {
        System.out.println(
"destory.");
    }

}

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 -->
    
<context:annotation-config />
    
<bean id="u" class="com.bebig.dao.impl.UserDAOImpl"  />
    
<bean id="u2" class="com.bebig.dao.impl.UserDAOImpl"  />
    
<bean id="u3" class="com.bebig.dao.impl.UserDAOImpl" >
    
<!-- 通过qualifier来指定id -->
        
<qualifier value="main"></qualifier>
    
</bean>

    
<bean id="userService" class="com.bebig.service.UserService">

    
</bean>

</beans>
 

1.     @Autowired

a)     默认按类型byType

b)     如果想用byName,使用@Qualifier

c)     写在private field(第三种注入形式)(不建议,破坏封装)

d)     如果写在set上,@qualifier需要写在参数上