首页 > 代码库 > spring案列——annotation配置

spring案列——annotation配置

一、需要的jar包

spring.jar

commons-loggin.jar

commons-loggin.jar

commons-annotation.jar

二、项目结构

技术分享

 

三、entity

 

package com.team.model;

public class User {

	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

  

四、dao

 

package com.team.dao;

import com.team.model.User;

public interface UserDAO {
public void print();
}

  

package com.team.dao;

import org.springframework.stereotype.Component;

import com.team.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO{

	
	
	@Override
	public void print() {
		System.out.println("auto");
	}


	
	
}

  

五、service

 

package com.team.service;


import com.team.model.User;

public interface UserService {

	public void add();
	
}

  

package com.team.service;


import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component("userService")
public class UserServiceImpl implements UserService{

	private UserDAO userDAO;
	
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="u")
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	
	
	

	public void add()
	{
		userDAO.print();
		
	}
}

  

六、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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

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


</beans>
  

  

七、测试

 

package com.team.service;





import static org.junit.Assert.*;

import org.junit.Test;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserServiceTest {

	@Test
	public void testAdd() {
		ApplicationContext ap=new ClassPathXmlApplicationContext("beans.xml");
		UserService u=(UserService) ap.getBean("userService");
		u.add();
	}

}

  

八、效果

技术分享

 

@Component:类似把bean放进容器中

@Resource、@Autowired:从容器取出对象

spring案列——annotation配置