问题引出:如何简化传统spring项目的配置?
解决方式:
spring framwor团队为了解决上述问题,生产出了springboot框架
引发思考:
1、springboot 如何简化了【web mvc】的开发配置过程?
1.1、依赖问题:aop,beans,mvc如何导入:在springboot提供的看得到的依赖(starter)中包含了spring核心依赖
1.2、如何编写维护bean的核心配置文件
代替applicationContext.xml
注解编程
- 单独的一个bean
@configuration //代表当前类等同于applicationcontext.xml
public class Myconfig{
public Person person(){
Person person=new Person();
person.setusername("jack");
person.setpassword("123456");
return person;
}
}
AnnotationconfigApplicationcontext context=new AnnotationconfigApplicationcontext (Myconfig.class);
Person person=(Person)context.getBean("person"); //加载Spring的应用上下文
- 多个bean[当前工程中]
如何批量管理多个bean,比如某包下有100个bean,难道要像上述情况一样,一个个加载吗?显然不合理,springmvc.xml当中有进行包扫描,如果该包之下的bean有加 @controller,@Service,@reposigtory,@component 注解,那么将这些bean交给ioc容器管理,那在springboot当中如何使用?也使用注解编程:@ComponentScan,从而达到批量扫描的作用
Tip
1、@Configuration也相当于@Component,所以也会交给IOC容器管理,因为@Configuration注解里面加了@Component注解
@ComponentScan不加路径默认扫描类根目录,即类的此包
拥有以下两个注解就可达到批量把业务代码的bean交给IOC容器
Configuration
@ComponentScan
关于@SpringBootApplication启动类注解,包含了上述两个注解,扫描启动类的根目录
- 多个bean[非当前工程中]
在第三方jar包中的bean如何加载进spring容器,相应的配置文件如何继承,例如集成mybatis,spring boot如何解决这个问题?
解决方法:spring boot预留一个扩展接口,通过实现接口ImportSelector完成
注解编程:使用@import注解
EnableAutoConfiguration :自动装配操作过程
@Import({AutoConfigurationImportSelector.class})
AutoConfigurationImportSelector#selectImports
//写入第三方jar包位置
getCandidateConfigurations(annotationMetadata, attributes)
SpringFactoriesLoader.loadFactoryNames-->找配置文件,配置文件中定义了这些bean的路径
//spring boot启动时候,就会调用上述方法,寻找项目中所有的spring.factories文件也就是定义了第三方bean的全路径的配置文件
META-INF/Spring.factories 第三方jar包必须有这个目录,springboot才能帮你自动装配到ioc容器中
spring.factories需要定义一个入口配置类,@bean将当前jar包的所有bean罗列出来 ---->@configuration+@Bean
2、starters思想
原生第三方的组件并没有spring.factories文件,故springboot团队重写了第三方jar包,增加了spring.factories文件,以及原本可以在第三方组件中进行的配置,这便是starers思想