1. 程式人生 > >spring05——基於註解的方式配置bean

spring05——基於註解的方式配置bean

Spring可以從classPath下自動掃描,偵測和例項化具有特定註解的元件;

特定的元件包括:

[email protected]:基本註解,標識一個首Spring管理得元件

[email protected]:標識持久化元件

[email protected]:標識服務層元件

[email protected]:標識表現層元件

Spring有預設的命名策略,即第一個字母小寫,也可以在註解中通過value屬性命名。

在元件上使用註解後需要在Spring配置檔案中宣告<Context:component-scan>自動掃描包路徑下的元件

舉例:

UserAction——UserService——UserDao

xml:

base-package:要掃描包的全路徑

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

	<!-- 配置自動掃描的包: 需要加入 aop 對應的 jar 包 -->
	<context:component-scan base-package="com.atguigu.spring.annotation"></context:component-scan>

</beans>

輸出:

 

 

需要注意的是@Autowired可以標註在屬性上也可以標註在set方法上,預設情況下所有使用@Autowired的註解都需要被設定,當Spring找不到匹配的bean裝配屬性時,會拋異常,若某一屬性允許不被設定需要將@Autowired的required屬性設定為false;

此外當IOC容器中存在多個同類型的Bean時,通過型別進行的自動裝配將會好不到對應的bean,此時可以在@Qualifier註解裡提供Bean的名稱(Spring允許對set方法的入參設定@Qualifier已指定注入的Bean名稱)

例如這種情況:

兩個imp實現同一類BaseService

 

編寫 controller:

Main方法:

執行時錯誤:

修改Controller為@Autowired 新增 @Qualifier屬性 指定要配置的bean,注意預設的命名規則

或者:

輸出:

 

 

 

下面在說說泛型依賴注入:

這個很簡單,結構圖如下:

BaseDao:

package com.atguigu.spring.annotation.generic;

public class BaseDao<T> {

	public void save(T entity){
		System.out.println("Save:" + entity);
	}
	
}

BaseService:

BaseService 注入BaseDao

package com.atguigu.spring.annotation.generic;

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

public class BaseService<T> {

	@Autowired
	private BaseDao<T> dao;
	
	public void addNew(T entity){
		System.out.println("addNew by " + dao);
		dao.save(entity);
	}
	
}

 

UserDao繼承BaseDao:

package com.atguigu.spring.annotation.generic;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao extends BaseDao<User>{

}

 

UserService 繼承BaseService

package com.atguigu.spring.annotation.generic;

import org.springframework.stereotype.Service;

//若註解沒有指定 bean 的 id, 則類名第一個字母小寫即為 bean 的 id
@Service
public class UserService extends BaseService<User>{

}

Main:

UserService userService = (UserService) ctx.getBean("userService");
		userService.addNew(new User());

 

輸出: