在本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>
下载源代码
标签: 春天
翻译自: https://mkyong.com/spring/spring-filtering-components-in-auto-scanning/