日期:2014-05-17  浏览次数:20667 次

spring集合注入与scope问题
Java code

public class User {

    private int id;
    private String name;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}



Java code
public class UserService {
    private Set<User> userSet = new HashSet<User>();
    private List<User> userList = new ArrayList<User>();
    private Map<String,User> userMap = new HashMap<String,User>();
    
    public Set<User> getUserSet() {
        return userSet;
    }

    public void setUserSet(Set<User> userSet) {
        this.userSet = userSet;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public Map<String, User> getUserMap() {
        return userMap;
    }

    public void setUserMap(Map<String, User> userMap) {
        this.userMap = userMap;
    }

    public UserService(){
        
    }
    }


XML code
<bean name="user" class="com.hiway.entity.User" scope="prototype">
        <property name="id" value="123"></property>
        <property name="name" value="Hiway"></property>
    </bean>  

    <bean name="userService" class="com.hiway.entity.UserService" scope="prototype">
        <property name="userSet">
            <set>
                <ref bean="user"/>
                <ref bean="user"/>
                <ref bean="user"/>
            </set>
        </property>
        <property name="userList">
            <list>
                <ref bean="user"/>
                <ref bean="user"/>
                <ref bean="user"/>
            </list>
        </property>
        
        <property name="userMap">
            <map>
                <entry key="1">
                    <ref bean="user"/>
                </entry>
                <entry key="2">
                    <ref bean="user"/>
                </entry>
                <entry key="3">
                    <ref bean="user"/>
                </entry>
            </map>
        </property>
    </bean>


测试类:
Java code
UserService service = (UserService) context.getBean("userService");
        
        System.out.println("userSet:===================");
        Iterator it = service.getUserSet().iterator();
        while(it.hasNext()){
            User u = (User) it.next();
            System.out.println(u);
        }
        
        System.out.println("userList:=================");
        it = service.getUserList().iterator();
        while(it.hasNext()){
            User u = (User) it.next();
            System.out.println(u);
        }
        
        System.out.println("userMap:==============");
        it = service.getUserMap().entrySet().iterato