1.基于注解的配置bean
元件掃描(component scanning):Spring能夠從classpath下自動掃描,偵測和執行個體化具有特定注解的元件
元件包括:
[email protected]:基本注解,表示一個受Spring管理的元件
[email protected]:辨別持久層元件
[email protected]:辨別服務層(業務層)元件
[email protected]:辨別表現層元件
使用注解後,還需要在Spring配置檔案中聲明<context:component-scan>
-base-package屬性指定一個需要掃描的基類包,Spring容器将會掃描這個基類包及其自爆中的所有類
-當需要掃描多個包時,使用逗号分隔
例如:一個基于注解的Bean
@Component //受Spring管理的元件
public class testObject {
}
建立一個接口:UserRespository
public interface UserRepository {
void save();
}
這個接口Impl,持久層
@Repository(value="userRespository")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("UserRepository begin~~~~~~");
}
}
寫一個業務層
@Service
public class UserService {
public void add(){
System.out.println("UserService begin~~~~");
}
}
寫一個Controller
@Controller
public class UserController {
public void executable(){
System.out.println("UserController begin");
}
}
配置檔案中配置自動掃描的包:
<context:component-scan base-package="cn.spring.study03.*" />
-如果僅希望掃描特定的類而非基包下的所有類,可使用resource-pattern屬性過濾特定的類,示例:
<context:component-scan base-package="com.spring.beans"
resource-pattern="repository/*.class"/>
-<context:include-filter>子節點表示要包含的目标類
-<context:exclude-filter>子節點表示要排除在外的目标類
支援多種類型的過濾表達式
annotation com.spring.XxxAnnotation 所有标注了XxxAnnotation的類,該類型采用目标類是否标注了某個注解進行過濾
assinable com.spring.XxxService 所有繼承或擴充XxxService的類,該類型采用目标類是否繼承或擴充某個特定類進行過濾
aspectj com.spring.*Service+ 所有類名以Service結束的類及繼承或擴充它們的類。該類型采用Aspectj表達式進行過濾
regex com.spring.anno... 所有com.spring.anno包下的類,該類型采用正規表達式根據類的類名進行過濾
custom com.spring.XxxTypeFilter 采用XxxTypeFilter通過代碼的方式定義過濾規則。該類必須實作org.springframework.core.type.TypeFilter接口
<!--context:exclude-filter 子節點指定排除哪些指定表達式元件-->
<context:component-scan base-package="com.spring.annotation">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
注意:預設情況下ClassPathBeanDefinitionScanner會注冊對@Component、@ManagedBean的bean進行掃描,因為use-default-filter預設為true
假設在一個包下包含多種注解的Bean,這裡僅僅設定了需要掃描到@Controller,這是可以通過将use-default-filter設定為false即可
2.泛型依賴注入,是spring 4.0引入的新功能
一個典型的例子,首先建立BaseRepository<T>和BaseService<T>
public class BaseRepository<T> {
}
public class BaseService<T> {
@Autowired
protected BaseRepository<T> repository;
public void add(){
System.out.println("add...");
System.out.println(repository);
}
}
在建立UserRepository繼承BaseRepository,和UserService繼承BaseService,讓他們交給IOC容器處理
@Repository
public class UserRepository extends BaseRepository<User>{
}
@Service
public class UserService extends BaseService<User>{
}
配置檔案即可