Spring IOC容器-註解的方式【更簡化】

鬆門一枝花發表於2016-05-09

----更加簡化的版本

UserAction.java

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

//@Component("userAction")  // 加入IOC容器

//@Component

@Controller  // 控制層的元件
public class UserAction {

	@Resource
	private UserService userService;

	public String execute() {
		userService.save();
		return null;
	}
}


UserService.java

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

//@Component("userService")  // userService加入ioc容器

//@Component

@Service   // 表示業務邏輯層的元件
public class UserService {
	
//	@Resource	//  根據型別查詢 【在容器中要確保該型別只有一個變數】
	
	@Resource(name = "userDao")  // 根據名稱查詢
	private UserDao userDao;  // 去容器中招UserDao型別的變數,找到後就賦值

	public void save() {
		userDao.save();
	}
}

UserDao.java

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

// 把當前物件加入ioc容器
//@Component("userDao")   //  相當於bean.xml 【<bean id=userDao class=".." />】

//@Component  // 加入ioc容器的UserDao物件的引用名稱, 預設與類名一樣, 且第一個字母小寫

@Repository   // 在持久層可以選擇用這個註解
public class UserDao {
	
	public UserDao(){
		System.out.println("UserDao.UserDao()");
	}
	
	public UserDao(int id){
		System.out.println("UserDao.UserDao(int id)" + id);
	}

	public void save() {
		System.out.println("zengmg:儲存使用者!!!");
	}
}


bean.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- 開啟註解掃描 -->
	<context:component-scan base-package="zengmg.e_anno2"></context:component-scan>
	
	<bean id="userDao" class="zengmg.UserDao" scope="prototype">
	</bean>
	
	
</beans>   

測試程式碼:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

	// 建立容器物件
	private ApplicationContext ac = 
		new ClassPathXmlApplicationContext("zengmg/e_anno2/bean.xml");

	@Test
	public void testExecuteAction() {
		// 從容器中獲取Action
		UserAction userAction = (UserAction) ac.getBean("userAction");
		userAction.execute();
	}
}


相關文章