spirng学习
二: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的类型
-
注解形式的FilterType.ANNOTATION
@Controller @Service @Repository @Compent -
指定类型的 FilterType.ASSIGNABLE_TYPE
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {xxxService.class}) -
aspectj类型的 FilterType.ASPECTJ(不常用)
-
正则表达式的 FilterType.REGEX(不常用)
-
自定义的 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 { }