Spring注解——使用@ComponentScan自動(dòng)掃描組件

1.創(chuàng)建一個(gè)配置類,在配置類上添加 @ComponentScan 注解。該注解默認(rèn)會(huì)掃描該類所在的包下所有的配置類,相當(dāng)于之前的 <context:component-scan>。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class BeanConfig {

}

2.使用 ApplicationContext 的 getBeanDefinitionNames() 方法獲取已經(jīng)注冊(cè)到容器中的 bean 的名稱。

import io.mieux.config.BeanConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App02 {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(BeanConfig.class);

        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanDefinitionNames) {
            System.out.println("beanName: " + beanName);
        }
    }
}

運(yùn)行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig

除了 spring 本身注冊(cè)的一些 bean 之外,可以看到最后一行,已經(jīng)將 BeanConfig 這個(gè)類注冊(cè)進(jìn)容器中了。

3.指定要掃描的包(使用@ComponentScan 的 valule 屬性來(lái)配置),創(chuàng)建一個(gè)controller 包,并在該包下新建一個(gè) AppController 類。

package io.mieux.controller;

import org.springframework.stereotype.Controller;

@Controller
public class AppController {
}

在類上加了@Controller注解,說(shuō)明該類是一個(gè) Component。在 BeanConfig 類中修改:

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan(value = "io.mieux.controller")
public class BeanConfig {

}

在 @ComponentScan 注解中指定了要掃描的包。

運(yùn)行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig
beanName: appController

AppController 已經(jīng)被注冊(cè)進(jìn)容器了。

4.excludeFilters 和 includeFilters 的使用

使用 excludeFilters 來(lái)按照規(guī)則排除某些包的掃描。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

@ComponentScan(value = "io.mieux",
        excludeFilters = {@Filter(type = FilterType.ANNOTATION,
        value = {Controller.class})})
public class BeanConfig {

}

excludeFilters 的參數(shù)是一個(gè) Filter[] 數(shù)組,然后指定 FilterType 的類型為 ANNOTATION,也就是通過(guò)注解來(lái)過(guò)濾,最后的 value 則是Controller 注解類。配置之后,在 spring 掃描的時(shí)候,就會(huì)跳過(guò) io.mieux 包下,所有被 @Controller 注解標(biāo)注的類。

使用 includeFilters 來(lái)按照規(guī)則只包含某些包的掃描。

在創(chuàng)建一個(gè) service 的包,并創(chuàng)建一個(gè) AppService 類,再加上一個(gè) @Service 注解。

package io.mieux.service;

import org.springframework.stereotype.Service;

@Service
public class AppService {
}

修改 BeanCofig 類:

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

@ComponentScan(value = "io.mieux", includeFilters = {@Filter(type = FilterType.ANNOTATION, classes = {Controller.class})})
public class BeanConfig {

}

運(yùn)行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig
beanName: appController
beanName: appService

配置里面,應(yīng)該是只包含 @Controller 注解的類才會(huì)被注冊(cè)到容器中,為什么 @Service 注解的類也被注冊(cè)了呢?這里涉及到 @ComponentScan 的一個(gè) useDefaultFilters 屬性的用法,該屬性默認(rèn)值為 true,也就是說(shuō) spring 默認(rèn)會(huì)自動(dòng)發(fā)現(xiàn)被 @Component、@Repository、@Service 和 @Controller 標(biāo)注的類,并注冊(cè)進(jìn)容器中。要達(dá)到只包含某些包的掃描效果,就必須將這個(gè)默認(rèn)行為給禁用掉(在 @ComponentScan 中將 useDefaultFilters 設(shè)為 false 即可)。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

@ComponentScan(value = "io.mieux", 
        includeFilters = {@Filter(type = FilterType.ANNOTATION, classes = {Controller.class})},
        useDefaultFilters = false)
public class BeanConfig {

}

運(yùn)行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig
beanName: appController

5.添加多種掃描規(guī)則

1、如果使用的 jdk8,則可以直接添加多個(gè) @ComponentScan 來(lái)添加多個(gè)掃描規(guī)則,但是在配置類中要加上 @Configuration 注解,否則無(wú)效。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan(value = "io.mieux.controller")
@ComponentScan(value = "io.mieux.service")
@Configuration
public class BeanConfig {

}

2、也可以使用 @ComponentScans 來(lái)添加多個(gè) @ComponentScan,從而實(shí)現(xiàn)添加多個(gè)掃描規(guī)則。同樣,也需要加上 @Configuration 注解,否則無(wú)效。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;

@ComponentScans(value = 
        {@ComponentScan(value = "io.mieux.controller"),
        @ComponentScan(value = "io.mieux.service")})
@Configuration
public class BeanConfig {

}

6.添加自定義過(guò)濾規(guī)則

在前面使用過(guò) @Filter 注解,里面的 type 屬性是一個(gè) FilterType 的枚舉類型:

public enum FilterType {

    ANNOTATION,
    ASSIGNABLE_TYPE,
    ASPECTJ,
    REGEX,
    CUSTOM

}

使用 CUSTOM 類型,就可以實(shí)現(xiàn)自定義過(guò)濾規(guī)則。

1、 首先創(chuàng)建一個(gè)實(shí)現(xiàn) TypeFilter 接口的 CustomTypeFilter 類,并實(shí)現(xiàn)其 match 方法。

package io.mieux.config;

import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;

public class CustomTypeFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader,
                         MetadataReaderFactory metadataReaderFactory) throws IOException {

        // 獲取當(dāng)前掃描到的類的注解元數(shù)據(jù)
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        // 獲取當(dāng)前掃描到的類的元數(shù)據(jù)
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        // 獲取當(dāng)前掃描到的類的資源信息
        Resource resource = metadataReader.getResource();

        if (classMetadata.getClassName().contains("Co")) {
            return true;
        }

        return false;
    }
}

這里簡(jiǎn)單對(duì)掃描到的類名進(jìn)行判斷,如果類名包含”Co“的就符合條件,也就會(huì)注入到容器中。

2、對(duì) BeanConfig 進(jìn)行修改,指定過(guò)濾類型為 Custom 類型,并指定 value 為 CustomTypeFilter.class。

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

@ComponentScan(value = "io.mieux",
        includeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, value = {CustomTypeFilter.class})},
        useDefaultFilters = false)
public class BeanConfig {

}

運(yùn)行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig
beanName: appController
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容