假设在某个包下有很多Bean,有的Bean上标注了Component,有的标注了Controller,有的标注了Service,有的标注了Repository,现在由于某种特殊业务的需要,只允许其中所有的Controller参与Bean管理,其他的都不实例化。这应该怎么办呢?
packagecom.powernode.spring6.bean3;importorg.springframework.stereotype.Component;importorg.springframework.stereotype.Controller;importorg.springframework.stereotype.Repository;importorg.springframework.stereotype.Service;@ComponentpublicclassA{publicA(){System.out.println("A的无参数构造方法执行");}}@ControllerclassB{publicB(){System.out.println("B的无参数构造方法执行");}}@ServiceclassC{publicC(){System.out.println("C的无参数构造方法执行");}}@RepositoryclassD{publicD(){System.out.println("D的无参数构造方法执行");}}@ControllerclassE{publicE(){System.out.println("E的无参数构造方法执行");}}@ControllerclassF{publicF(){System.out.println("F的无参数构造方法执行");}}我只想实例化bean3包下的Controller。配置文件这样写:
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:component-scanbase-package="com.powernode.spring6.bean3"use-default-filters="false"><context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan></beans>use-default-filters=“true” 表示:使用spring默认的规则,只要有Component、Controller、Service、Repository中的任意一个注解标注,则进行实例化。
use-default-filters=“false”表示:不再spring默认实例化规则,即使有Component、Controller、Service、Repository这些注解标注,也不再实例化。
<context:include-filter type=“annotation” expression=“org.springframework.stereotype.Controller”/> 表示只有Controller进行实例化。
@TestpublicvoidtestChoose(){ApplicationContextapplicationContext=newClassPathXmlApplicationContext("spring-choose.xml");}执行结
也可以将use-default-filters设置为true(不写就是true),并且采用exclude-filter方式排出哪些注解标注的Bean不参与实例化:
<context:component-scanbase-package="com.powernode.spring6.bean3"><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Repository"/><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Service"/><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan>