spring @Resource

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>
	
	

  <bean name="ud" class="com.bjsxt.dao.impl.UserDAOImpl">
	</bean>
  <bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">
	</bean>

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

  <!--<property name="userDAO" ref="userDAO"> </property>   -->
  </bean>

</beans>

userservice

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

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



public class UserService {
	private UserDAO userDAO;  
	public void add(User user) {
		userDAO.save(user);
	}
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="ud")
	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("userService");

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



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