自动扫描中的Spring Filter组件

在本Spring自动组件扫描教程中 ,您将学习如何使Spring自动扫描组件。 在本文中,我们向您展示了如何在自动扫描过程中进行组件过滤。

1.过滤器组件–包括

参见以下示例,使用Spring“ 过滤 ”来扫描和注册与定义的“ regex”匹配的组件名称,即使该类未使用@Component进行注释。

DAO层

package com.mkyong.customer.dao;

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

服务层

package com.mkyong.customer.services;

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

public class CustomerService 
{
	@Autowired
	CustomerDAO customerDAO;

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

弹簧过滤。

<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.mkyong" >

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

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

	</context:component-scan>

</beans>

运行

package com.mkyong.common;

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

import com.mkyong.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.mkyong.customer" >
		<context:exclude-filter type="annotation" 
			expression="org.springframework.stereotype.Service" />		
	</context:component-scan>

排除那些包含DAO字的文件名。

<context:component-scan base-package="com.mkyong" >
		<context:exclude-filter type="regex" 
			expression="com.mkyong.customer.dao.*DAO.*" />		
	</context:component-scan>

下载源代码

下载它-Spring-Filter-Auto-Scan-Example.zip

翻译自: https://mkyong.com/spring/spring-filtering-components-in-auto-scanning/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值