spring自动添加注解

来源:互联网 发布:匡恩网络是个奇葩公司 编辑:程序博客网 时间:2024/05/01 18:34

pring Filter Components In Auto Scanning —— 在自动扫描中过滤组件

Filter Component——include

下例演示了用“filter”自动扫描注册组件,这些组件只要匹配定义的“regex”的命名规则,Clasee前就不需要用@Component进行注释。

DAO层,CustomerDAO.java如下:

package com.lei.customer.dao;public class CustomerDAO {    @Override    public String toString() {        return "Hello , This is CustomerDAO";    }    }

Service层,CustomerService.java如下:

package com.lei.customer.services;import org.springframework.beans.factory.annotation.Autowired;import com.lei.customer.dao.CustomerDAO;public class CustomerService {    @Autowired    CustomerDAO customerDAO;    @Override    public String toString() {        return "CustomerService [customerDAO=" + customerDAO + "]";    }}

Spring Filtering,xml配置如下:

<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.lei" >        <context:include-filter type="regex"                        expression="com.lei.customer.dao.*DAO.*" />        <context:include-filter type="regex"                        expression="com.lei.customer.services.*Service.*" />    </context:component-scan></beans>

以上xml文件中,所有文件名字,只要包含DAO和Service(DAO.Service.)关键字的,都将被检查注册到Spring容

运行以下代码:

package com.lei.common;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.lei.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]

Filter Component——exclude

你也可以用exclude,制定组件避免被Spring发现并被注册到容器中。

以下配置排除用@Service注释过的组件

<context:component-scan base-package="com.lei.customer" >        <context:exclude-filter type="annotation"             expression="org.springframework.stereotype.Service" />        </context:component-scan>
<context:component-scan base-package="com.lei" >        <context:exclude-filter type="regex"             expression="com.lei.customer.dao.*DAO.*" />        </context:component-scan>
0 0
原创粉丝点击