【Spring注解】@Configuration和@ComponentScan注解

Spring注解

一、组建注册

包结构:

【Spring注解】@Configuration和@ComponentScan注解_第1张图片

1.@Configuration和@ComponentScan

@ComponentScan的includeFilters用法

FilterType的类型

ANNOTATION,基于注解的过滤
ASSIGNABLE_TYPE,指定class
ASPECTJ,ASPECTJ表达shi
REGEX,正则表达式
CUSTOM;自定义
//相当于application-bean.xml
@Configuration 
//配置扫描包的策略,当前注解为只扫描加@Controller的组件
//注意useDefaultFilters要设置为fasle,不然为默认的Filters,@Service/@Repository都扫描
@ComponentScan(value = "com.gaoyuzhe",includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)
},
        useDefaultFilters = false)

运行结果

【Spring注解】@Configuration和@ComponentScan注解_第2张图片

excludeFilters用法:

注意:useDefaultFilters设置为true,不然不会扫描到组件

package com.gaoyuzhe.config;

import com.gaoyuzhe.pojo.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

/**
 * @author GaoYuzhe
 * @date 2018/3/12.
 */
@Configuration
@ComponentScan(value = "com.gaoyuzhe",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)
},
        useDefaultFilters = true)
public class MainConfig {

    @Bean
    public Person person(){
        return new Person("gaoyuzhe ",12);
    }
}

运行结果

【Spring注解】@Configuration和@ComponentScan注解_第3张图片

自定义Filter策略

/**
 * 自定义的过滤规则
 * @author GaoYuzhe
 * @date 2018/3/12.
 */
public class MyTypeFilter implements TypeFilter {
    /**
     * 匹配规则
     * @param metadataReader the metadata reader for the target class
     *                       当前类的信息
     * @param metadataReaderFactory  a factory for obtaining metadata readers
     *                                for other classes (such as superclasses and interfaces)
     *                               当前类的父类或者接口的信息
     * @return 是否匹配
     * @throws IOException
     */
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //当前类名称
        String className = classMetadata.getClassName();
        System.out.println("className = " + className);
        //当前类的资源路径
        Resource resource = metadataReader.getResource();
        System.out.println("resource = " + resource);
        //如果类名包含"Dao",则为匹配成功
        return className.contains("Dao");
    }
}

配置类注解。

 @Configuration
 @ComponentScan(value = "com.gaoyuzhe",includeFilters = {
         @ComponentScan.Filter(type = FilterType.CUSTOM,classes = MyTypeFilter.class)
 }, useDefaultFilters = false)

执行结果
【Spring注解】@Configuration和@ComponentScan注解_第4张图片

你可能感兴趣的:(Spring注解)