目录
1 了解SpringBoot
- 属于Spring家族。
- 快速开发框架,可以快速搭建一套基于SpringBoot框架体系的应用。
- 自动装配,无需手动引入全部依赖
- 项目可独立运行,内置容器,无需外部引入
2 SpringBoot快速入门
1、创建一个maven项目
2、在pom.xml中,必须先将parent设为是springboot的parent,该parent包含了大量默认的配置,大大简化了开发。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
在<dependencies>标签中引入web-start 依赖 ,版本可省略,默认和上方parent的版本号一致
<!--web starter 依赖的引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、编写应用
创建一个controller层,返回浏览器一个字符串“Hello,SpringBoot”
@Controller
public class helloController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "Hello,SpringBoot";
}
}
4、创建启动类
@SpringBootApplication注解表示标识这个类是整个项目的启动类(启动类只有一个,里面有main方法)运行就直接点击运行按钮就可以直接启动
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
System.out.println("Hello World!");
}
}
5、结果演示
在浏览器中输入对应地址信息,查看是否有信息展示
6、目录展示
3 SpringBoot整合mybatis
1、引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
2、在resources文件夹下添加配置文件 application.yml,里面主要配置sql信息
#配置数据源spring:
spring:
datasource:
# 配置数据库驱动的全限定名
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/study
username: root
password: 123456
mybatis:
# XML配置文件的位置
mapper-locations: classpath:mapper/*.xml
3、创建pojo类student类,属性和数据库中表的属性要对应
public class student {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4、Mapper包中创建一个接口StudentMapper
@Mapper
public interface StudentMapper {
List<student> selectAllStudents();
}
5、在resources文件包下创建一个mapper包,里面放入StudentMapper.xml
这里放入要执行的sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.che.mapper.StudentMapper">
<select id="selectAllStudents" resultType="com.che.pojo.student">
select * from student
</select>
</mapper>
6、创建service层,StudentService
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public List<student> findAll(){
return studentMapper.selectAllStudents();
}
}
7、编写controller层,StudentController
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/list")
@ResponseBody
public List<student> list(){
return studentService.findAll();
}
}
8、启动运行,在浏览器中输入相应的地址,得到数据库中得内容
9、目录展示
4 自动装配
通常项目的启动类名为:XXApplication,在这个启动类中注解@SpringBootApplication 是负责开启组件扫描注解和自动装配, SpringApplication.run()是负责启动引导应用程序。
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
重点分析一下@SpringBootApplication注解。
该注解由组合注解组成。
主要的注解是@SpringBootConfiguration(配置类,类似于spring中得@Configuration注解)、@EnableAutoConfiguration(开启自动装配)、
@ComponentScan(完成包的扫描,因此整个项目的启动类必须要放在和处理业务逻辑文件夹同一目录下,保证所有涉及的类可以被扫描到)。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
……}
①@SpringBootConfiguration注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
这个注解只是将spring中的@Configuration注解做了一个包装,作用完全相同,表明该类是Java中得一个配置类。
②@ComponentScan注解
该注解对应xml配置中的元素,功能主要是自动扫描并加载符合条件的组件或者bean的定义,最终将bean装配到IOC容器中,默认spring框架实现是从声明@ComponentScan所在的类的包路径进行扫描。
③@EnableAutoConfiguration注解
这个是自动装配的核心
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@EnableAutoConfiguration注解中的核心又在于借助import注解,来收集和注册特定场景相关的bean的定义,@Import({EnableAutoConfigurationImportSelector.class})。
那里面的参数类EnableAutoConfigurationImportSelector又是干什么用的?借助当前类来完成将所有符合条件的配置都加载到springboot中创建并使用的容器中。这又借助于spring框架原有的工具类SpringFactoriesLoader的支持。
SpringFactoriesLoader是完成类的加载,在指定的配置文件METF-INF/spring.factories,加载autoConfiguration的配置通过反射来实例化@Confoguration,判断是否需要加载具体信息
核心方法:
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
try {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
configurations = this.sort(configurations, autoConfigurationMetadata);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.filter(configurations, autoConfigurationMetadata);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return (String[])configurations.toArray(new String[configurations.size()]);
} catch (IOException var6) {
throw new IllegalStateException(var6);
}
}
}
分析DataSourceAutoConfiguration
来了解SpringBoot如何自动装配
在自动装配类中或有很多条件性注解:
@ConditionalOnBean:当容器里有指定的bean的条件下才会进行注解加载。
@ConditionalOnClass:当类路径下有指定的类的条件下才会进行注解加载。
@ConditionalOnProperty:指定的属性是否有指定的值才会进行注解加载。
@Configuration
@ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
@EnableConfigurationProperties({DataSourceProperties.class})
@Import({Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class})
public class DataSourceAutoConfiguration {
private static final Log logger = LogFactory.getLog(DataSourceAutoConfiguration.class);
public DataSourceAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean
public DataSourceInitializer dataSourceInitializer(DataSourceProperties properties, ApplicationContext applicationContext) {
return new DataSourceInitializer(properties, applicationContext);
}
@EnableAutoConfiguration会导入EnableAutoConfigurationImportSelector类,而这个类的selectImports通过SpringFactoriesLoader得到大量配置类,而每一个配置上则根据条件配置来做出决策,以实现自动装配。