1)@Component
可以使用此註解描述 Spring 中的 Bean,但它是一個泛化的概念,僅僅表示一個組件(Bean),並且可以作用在任何層次。使用時只需將該註解標註在相應類上即可。
2)@Repository
用於將數據訪問層(DAO層)的類標識爲 Spring 中的 Bean,其功能與 @Component 相同。
3)@Service
通常作用在業務層(Service 層),用於將業務層的類標識爲 Spring 中的 Bean,其功能與 @Component 相同。
4)@Controller
通常作用在控制層(如 Struts2 的 Action),用於將控制層的類標識爲 Spring 中的 Bean,其功能與 @Component 相同。
5)@Autowired
用於對 Bean 的屬性變量、屬性的 Set 方法及構造函數進行標註,配合對應的註解處理器完成 Bean 的自動配置工作。默認按照 Bean 的類型進行裝配。
6)@Resource
其作用與 Autowired 一樣。其區別在於 @Autowired 默認按照 Bean 類型裝配,而 @Resource 默認按照 Bean 實例名稱進行裝配。
1. 創建 DAO 層接口
public interface PersonDao {
public void add();
}
2. 創建 DAO 層接口的實現類
@Repository("personDao")
public class PersonDaoImpl implements PersonDao {
@Override
public void add() {
System.out.println("Dao層的add()方法執行了...");
}
}
3. 創建 Service 層接口
public interface PersonService {
public void add();
}
4. 創建 Service 層接口的實現類
@Service("personService")
public class PersonServiceImpl implements PersonService {
@Resource(name = "personDao")
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
@Override
public void add() {
personDao.add();// 調用personDao中的add()方法
System.out.println("Service層的add()方法執行了...");
}
}
5. 創建 Action
@Controller("personAction")
public class PersonAction {
@Resource(name = "personService")
private PersonService personService;
public PersonService getPersonService() {
return personService;
}
public void add() {
personService.add(); // 調用personService中的add()方法
System.out.println("Action層的add()方法執行了...");
}
}
6. 創建 Spring 配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--使用context命名空間,通知spring掃描指定目錄,進行註解的解析-->
<context:component-scan base-package="com.mengma.annotation"/>
</beans>