LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code and KPI, Keep progress,make a better result.
Survive during the day and develop at night。
目录
概 述
一、IOC容器设计理念 依赖倒置原则。
<1>ioc的思想最核心的地方在于,资源不由使用资源的双方管理,而由不使用资源的第三方管理,这可以带来很多好处。
第一,资源集中管理,实现资源的可配置和易管理。
第二,降低了使用资源双方的依赖程度,也就是我们说的耦合度。
<2>BeanFacotry的bean是延时加载的,ApplicationContext是非延时加载的
二、spring IOC容器底层注解使用。
<1>基于读取配置类的形式定义Bean信息
@Configuration 配置类注解类似xml文件
@Bean 可以通过value给bean定义name
@ComponentScan
包扫描: basePackages = {"包的路径"}
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {TulingService.class})
}
包含用法: 需要把useDefaultFilters属性设置为false,
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
},useDefaultFilters = false
@ComponentScan.Filter type的类型(常用)
a)注解形式的FilterType.ANNOTATION
b)指定类型的 FilterType.ASSIGNABLE_TYPE
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {TulingService.class})
c)自定义 FilterType.CUSTOM
public class TestFilterType 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;
}
}
<2>、配置Bean的作用域对象
a、在不指定@Scope的情况下,所有的bean都是单实例的bean,而且是饿汉加载(容器启动实例就创建好了)
<1>singleton 默认单例
<2>prototype 多例 IOC容器启动的时候,并不会创建对象,而是在第一次使用的时候才会创建
b、@Lazy 主要针对单实例的bean 容器启动的时候,不创建对象,在第一次使用的时候才会创建该对象
<3>、IOC 容器中添加组件的方式
a、@CompentScan +@Controller @Service @Respository @compent
b、@Bean<4>、Bean的初始化方法和销毁方法.
c、@Import
@Bean(initMethod = "init",destroyMethod = "destroy")
针对单实例bean的话,容器启动的时候,bean的对象就创建了,而且容器销毁的时候,也会调用Bean的销毁方法
针对多实例bean的话,容器启动的时候,bean是不会被创建的而是在获取bean的时候被创建,而且bean的销毁不受IOC容器的管理
<5>、组件赋值 @Value + @PropertySource
@Value(“值”)
@Value("${person.lastName}")
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
<6>、自动装配
@AutoWired 可以标注在成员变量 set方法 及构造方法上
自动装配首先时按照类型进行装配,若在IOC容器中发现了多个相同类型的组件,那么就按照属性名称来进行装配
如果容器中没有,则会抛出异常 No qualifying bean of type ‘xxx’ available
若想不抛异常 ,我们需要指定 required为false的时候可以了 @Autowired(required = false)
小结
参考资料和推荐阅读
1.链接: 参考资料.