Spring過濾器元件自動掃描


在這個Spring自動元件掃描的教學,您已經了解如何使Spring自動掃描您的元件。在這篇文章中,我們將展示如何使用元件過濾器自動掃描過程。

1.過濾元件 - 包含

參見下面的例子中使用Spring 「過濾」 掃描並註冊匹配定義「regex」,即使該類元件的名稱未標註 @Component 。

DAO 層

package com.yiibai.customer.dao;

public class CustomerDAO 
{
	@Override
	public String toString() {
		return "Hello , This is CustomerDAO";
	}	
}

Service 層

package com.yiibai.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import com.yiibai.customer.dao.CustomerDAO;

public class CustomerService 
{
	@Autowired
	CustomerDAO customerDAO;

	@Override
	public String toString() {
		return "CustomerService [customerDAO=" + customerDAO + "]";
	}
		
}

Spring 過濾

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

	<context:component-scan base-package="com.yiibai" >

		<context:include-filter type="regex" 
                       expression="com.yiibai.customer.dao.*DAO.*" />

		<context:include-filter type="regex" 
                       expression="com.yiibai.customer.services.*Service.*" />

	</context:component-scan>

</beans>

執行

package com.tw511.common;

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

import com.yiibai.customer.services.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
		new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});

    	CustomerService cust = (CustomerService)context.getBean("customerService");
    	System.out.println(cust);
    	
    }
}

輸出

CustomerService [customerDAO=Hello , This is CustomerDAO]
在這個XML過濾中,所有檔案的名稱中包含 DAO 或 Service(*DAO.*, *Services.*) 單詞將被檢測並在 Spring 容器中註冊。

2.過濾元件 - 不包含

另外,您還可以排除指定元件,以避免 Spring 檢測和 Spring 容器註冊。不包括在這些檔案中標註有 @Service 。
<context:component-scan base-package="com.yiibai.customer" >
		<context:exclude-filter type="annotation" 
			expression="org.springframework.stereotype.Service" />		
	</context:component-scan>
不包括那些包含DAO這個詞組檔案名。
<context:component-scan base-package="com.yiibai" >
		<context:exclude-filter type="regex" 
			expression="com.yiibai.customer.dao.*DAO.*" />		
	</context:component-scan>

下載程式碼 – http://pan.baidu.com/s/1pKnzB2F