Spring篩檢程式組件自動掃描

在這個Spring自動組件掃描的教程,您已經瞭解如何使Spring自動掃描您的組件。在這篇文章中,我們將展示如何使用組件篩檢程式自動掃描過程。

1.過濾組件 - 包含

參見下麵的例子中使用Spring “過濾” 掃描並註冊匹配定義“regex”,即使該類組件的名稱未標注 @Component 。

DAO 層

package com.zaixian.customer.dao;

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

Service 層

package com.zaixian.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import com.zaixian.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.zaixian" >

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

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

	</context:component-scan>

</beans>

執行

package com.xuhuhu.common;

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

import com.zaixian.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.zaixian.customer" >
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
	</context:component-scan>
不包括那些包含DAO這個片語檔案名。
<context:component-scan base-package="com.zaixian" >
		<context:exclude-filter type="regex"
			expression="com.zaixian.customer.dao.*DAO.*" />
	</context:component-scan>


上一篇: Spring自動掃描組件 下一篇: Spring自動裝配Beans