spring @Resource + @Component

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">


<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.bjsxt"/>
	
	



</beans>

UserDAOImpl

package com.bjsxt.dao.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Component;

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

@Component("uu")
public class UserDAOImpl implements UserDAO {
	private Set<String> sets;
	private List<String> lists;
	private LinkedHashMap<String, String> maps;
	private String daoId;
	
	public String getDaoId() {
		return daoId;
	}


	public void setDaoId(String daoId) {
		this.daoId = daoId;
	}


	public Set<String> getSets() {
		return sets;
	}


	public LinkedHashMap<String, String> getMaps() {
		return maps;
	}


	public void setMaps(LinkedHashMap<String, String> maps) {
		this.maps = maps;
	}


	public void setSets(Set<String> sets) {
		this.sets = sets;
	}


	public List<String> getLists() {
		return lists;
	}


	public void setLists(List<String> lists) {
		this.lists = lists;
	}




	@Override
	public String toString() {
		// TODO Auto-generated method stub
		//return "sets size:" + sets.size() + "| lists size:" + lists.size() + "| maps size:" +  maps.size();
		return daoId;
		
	}


	public void save(User user) {
		//Hibernate
		//JDBC
		//XML
		//NetWork
		System.out.println("user saved!");
	}

}


userservice

package com.bjsxt.service;
import javax.annotation.Resource;

import org.springframework.stereotype.Component;

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


@Component("uuuService")
public class UserService {
	private UserDAO userDAO;  
	public void add(User user) {
		userDAO.save(user);
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="uu")
	public void setUserDAO( UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
}

test

package com.bjsxt.service;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.User;



public class UserServiceTest {

	@Test
	public void testAdd() throws Exception {
		BeanFactory applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		
		UserService service = (UserService)applicationContext.getBean("uuuService");

		service.add(new User());
	}
}


你可能感兴趣的:(spring @Resource + @Component)