网站建设情况总结,旅游网站效果图,国外优秀企业网站,公众平台登录文章目录 一、组件注册包扫描组件注解0#xff09;、 ComponentScans1#xff09;、 RestController2#xff09;、 Srevice3#xff09;、 Rerpository4#xff09;、Component 导入第三方包里的组件1#xff09;、Configuration1#xff09;、Bean1#xff09;、Cond… 文章目录 一、组件注册包扫描组件注解0、 ComponentScans1、 RestController2、 Srevice3、 Rerpository4、Component 导入第三方包里的组件1、Configuration1、Bean1、Conditional自定义条件类 Import 快速给容器导入一个组件1、Import2、interface ImportSelector3、ImportBeanDefinitionRegistrar 使用Spring提供的 FactoryBean1、interface FactoryBeanT 二、Bean生命周期创建初始化销毁1、相关注解和接口1、指定初始化和销毁方法2、实现初始化和销毁接口3、JSR2504、Bean后置处理器BeanPostProcessor 2、 Springd底层对BeanPostProcessor的使用 三、属性赋值PropertySourceValue 四、自动装配1、 AutowiredQualifier:指定需要装配的bean idPrimary优先装配该Bean构造器、方法、属性同样支持都是从容器中获取对应的Bean 2、ResourceJSR250规范3、IngectJSR3304、xxxAware把Spring底层组件自动注册到Bean中5、Profile根据环境配置给容器中注册组件 Spring官方文档 学习参考视频
一、组件注册
包扫描组件注解
0、 ComponentScans
ComponentScan Filter
1、 RestController
ResponseBodyController
2、 Srevice
3、 Rerpository
4、Component
导入第三方包里的组件
1、Configuration
1、Bean
Scopeprototype、singleton、request、sessionLazy
1、Conditional自定义条件类
Import 快速给容器导入一个组件
1、Import
2、interface ImportSelector
3、ImportBeanDefinitionRegistrar
使用Spring提供的 FactoryBean
1、interface FactoryBean
默认获取工厂bean调用getObject要获取工厂bean本身需要在id前添加
二、Bean生命周期
创建
单例模式容器初始化多礼模式从容器中获取实例
初始化
对象创建完成并赋值好属性之后
销毁
单实例容器关闭的时候多实例容器不会管理这个Bean需要自己手动调用
1、相关注解和接口
1、指定初始化和销毁方法
Bean(initMethodxxx, destroyMethodxxx)
2、实现初始化和销毁接口
interface InitializingBeaninterface DisposableBean
3、JSR250
PostConstructPreDestroy
4、Bean后置处理器BeanPostProcessor
interface BeanPostProcessorBean初始化前执行postProcessBeforeInitialization初始化后执行postProcessAfterInitialization整个在Bean赋值完成之后ApplicationContextAware接口注入ApplicationContext的实现就是该处理器完成
2、 Springd底层对BeanPostProcessor的使用
Bean赋值注入其他组件Autowired生命周期功能注解、接口
三、属性赋值
PropertySource
Value
基本数值SpEL#{}${}取出配置【yaml、properties】文件中的值需要先加载配置文件到环境中
四、自动装配
1、 Autowired
默认优先从容器中获取对应组件如果容器中存在多个相同类型Bean,根据名称注入Beanrequiredtrue必须false非必须由【AutowiredAnnotationBeanPostProcessor】处理器实现
Qualifier:指定需要装配的bean id
配合Autowired使用
Primary优先装配该Bean
配合Bean使用
构造器、方法、属性同样支持都是从容器中获取对应的Bean
标在构造器上如果组件只有一个有参构造器这个有参构造器的Autowired可以省略参数位置的组件还是默认从容器中装配标在属性上setf方法上标在方法Bean方法参数参数从容器中获取
2、ResourceJSR250规范
默认按照组件名称装配不支持required
3、IngectJSR330
需要引入pom依赖不支持required
4、xxxAware把Spring底层组件自动注册到Bean中
interface ApplicationContextAwareinterface BeanNameAwareinterface EmbeddedValueResolverAware
5、Profile根据环境配置给容器中注册组件
Dspring.profile.cativetesttest为环境变量代码方式容器启动前设置号参数 1、 AnnotationConfigApplicationContext annotationConfigApplicationContext new AnnotationConfigApplicationContext(); 2、 annotationConfigApplicationContext.getEnvironment().setActiveProfiles(“test”); 3、 annotationConfigApplicationContext.register(componentClasses); 4、 annotationConfigApplicationContext.refresh();可以添加在方法上也可以添加在类上