spring-Spring IOC 容器底层注解使用(2)

本文详细介绍了SpringIOC容器中注解的使用,包括基于配置类定义Bean、@ComponentScan注解的包扫描以及过滤规则。通过示例展示了如何排除和包含特定类型,并自定义FilterType实现更精确的扫描。了解这些内容有助于深入理解Spring框架的底层机制。
摘要由CSDN通过智能技术生成

二:Spring IOC 容器底层注解使用

去容器中读取Bean

public static void main( String[] args ) {
 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  System.out.println(ctx.getBean("person")); }

基于读取配置类的形式定义Bean信息

@Configuration public class MainConfig { 
	@Bean public Person person(){
		 return new Person(); 
	} 
}

注意: 通过@Bean的形式是使用的话, bean的默认名称是方法名,若@Bean(value=“bean的名称”) 那么bean的名称是指定的

去容器中读取Bean的信息(传入配置类)

public static void main( String[] args ) { 
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
	System.out.println(ctx.getBean("person")); 		 
}

在配置类上写@CompentScan注解来进行包扫描

@Configuration 
@ComponentScan(basePackages = {"com.xxxx.compentscan"}) 
public class MainConfig { }

①:排除用法 excludeFilters(排除@Controller注解的,和xxxService的)

排除@Controller注解的,和xxxxService

@ComponentScan(basePackages = {"com.xxx.compentscan"},excludeFilters = {   
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),  //过滤注解
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {xxxx.class}) //过滤指定类
}

②:包含用法 includeFilters ,注意,若使用包含的用法,需要把useDefaultFilters属性设置为false(true表示扫描全部的)

@ComponentScan(basePackages = {"com.xxxx.compentscan"},includeFilters= {
								 @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
							  },useDefaultFilters = false)
public class MainConfig { 

}

③ @ComponentScan.Filter type的类型

  1. 注解形式的FilterType.ANNOTATION
    @Controller @Service @Repository @Compent

  2. 指定类型的 FilterType.ASSIGNABLE_TYPE
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {xxxService.class})

  3. aspectj类型的 FilterType.ASPECTJ(不常用)

  4. 正则表达式的 FilterType.REGEX(不常用)

  5. 自定义的 FilterType.CUSTO
    (1) FilterType.CUSTOM 自定义类型如何使用

public class TulingFilterType implements TypeFilter {
	 @Override 
	 public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { 
	 //获取当前类的注解源信息
	  AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); 
	  //获取当前类的class的源信息 
	  ClassMetadata classMetadata = metadataReader.getClassMetadata(); 
	  //获取当前类的资源信息 Resource resource = metadataReader.getResource(); 
	  if(classMetadata.getClassName().contains("dao")) 
	  	 return true;
	    
	   return false; 
	}
}
@ComponentScan(basePackages = {"com.tuling.testcompentscan"},
			   includeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM,value = TulingFilterType.class) },useDefaultFilters = false) 
public class MainConfig { }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值