Spring 专题
专题目录
您的位置:java > Spring专题 > Spring过滤器组件自动扫描
Spring过滤器组件自动扫描
作者:--    发布时间:2019-11-20
在这个spring自动组件扫描的教程,您已经了解如何使spring自动扫描您的组件。在这篇文章中,我们将展示如何使用组件过滤器自动扫描过程。

1.过滤组件 - 包含

参见下面的例子中使用spring “过滤” 扫描并注册匹配定义“regex”,即使该类组件的名称未标注 @component 。

dao 层

package com.h3.customer.dao;

public class customerdao 
{
	@override
	public string tostring() {
		return "hello , this is customerdao";
	}	
}

service 层

package com.h3.customer.services;

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

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

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

	</context:component-scan>

</beans>

执行

package com.h3.common;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

import com.h3.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.h3.customer" >
		<context:exclude-filter type="annotation" 
			expression="org.springframework.stereotype.service" />		
	</context:component-scan>
不包括那些包含dao这个词组文件名。
<context:component-scan base-package="com.h3" >
		<context:exclude-filter type="regex" 
			expression="com.h3.customer.dao.*dao.*" />		
	</context:component-scan>


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册