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

Spring注解

一、组建注册

包结构:

image

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)

运行结果

9fmJS0.png

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);
    }
}

运行结果

excludeFilters用法

自定义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)

执行结果
执行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值