Spring自學第二天

1.基於註解的配置bean
  組件掃描(component scanning):Spring能夠從classpath下自動掃描,偵測和實例化具有特定註解的組件
  組件包括:
  -@Component:基本註解,表示一個受Spring管理的組件
  -@Respository:標識持久層組件
  -@Service:標識服務層(業務層)組件
  -@Controller:標識表現層組件
  使用註解後,還需要在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>{



配置文件即可  

  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章