1pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<dependency>
像上述此类starter,其实是一个总包,里面包含着所有相关类型的包,如:
spring-boot-starter-web包自动帮我们引入了web模块开发需要的相关jar包,
mybatis-spring-boot-starter帮我们引入了dao开发相关的jar包。
spring-boot-starter-xxx是官方提供的starter,xxx-spring-boot-starter是第三方提供的starter。
2数据源的配置(如Mysql/redis的配置):
以mybatis为列:
在传统的spring中,要有很多的bean来配置sqlsession,sqlsessionFactory或者事物等,但在springboot中:
只需在application.properties中配置如下即可:
spring.datasource.url=jdbc:mysql://localhost:3306/course?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=*****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8090
这是为什么?我们一步步来探究:
一:自动配置:基于java代码的bean配置:
打开mybatis-starter里的mybatisAutoConfiguration文件,发现里面有很多的
@Configuration和@bean,显然这是告诉spring我在这里要用java类来代替原本的xml配置
在原生的spring配置文件xml中,可能你会这样配置一个bean:
但在springboot中,你只需用@Configuration和@Bean配合即可,@bean告诉spring我要在这个方法中返回一个bean对象,加入到ioc容器中
同时,我们会看到在开头有很多的依赖注解,在网上查找资料如下:
二自动配置之bean参数的获取:
那么问题又来了,springboot如何获取前面写的application.properties中的配置参数?
打开DataSourceAutoConfiguration这个类,我们注意到使用了EnableConfigurationProperties这个注解
而在DatasourceProperties类中又发现有ConfigurationProperties这个注解:
在这个类中同时封装的各个数据源的属性:由此可见,springboot是通过@ConfigurationProperties读取配置,生成配置类又通过@EnableConfigurationProperties使@ConfigurationProperties下的配置类生效
三bean加载
如果要让一个普通类交给Spring容器管理,通常有以下方法:
1、使用 @Configuration与@Bean 注解
2、使用@Controller @Service @Repository @Component 注解标注该类,然后启用@ComponentScan自动扫描
3、使用@Import 方法
而springboot正是通过@Import的方法
总结:
我们可以将自动配置的关键几步以及相应的注解总结如下:
1、@Configuration&与@Bean->基于java代码的bean配置
2、@Conditional->设置自动配置条件依赖
3、@EnableConfigurationProperties与@ConfigurationProperties->读取配置文件转换为bean。
4、@EnableAutoConfiguration、@AutoConfigurationPackage 与@Import->实现bean发现与加载。