使用idea创建一个spring boot,会有一个启动类,一般名字会是(项目名+Application)
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}
这里有个注解@SpringBootApplication,等价于使用一下三个注解
- @Configuration:配置上下文,相当于把该类当做spring的xml配置文件中的<beans>
- @EnableAutoConfiguration:自动配置spring的上下文,通常会自动根据类路径和bean定义自动配置
- @ComponentScan:会自动扫描指定包下的全部@Component类,并注册成bean。包括下边的子注解@Service、@Repository、@Controller
@Configuration
基于JavaConfig方式的依赖关系绑定描述基本映射了基于XML的配置方式,比如:
基于 XML 的配置方式是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean定义 -->
<bean id="mockService" class="..MockServiceImpl">
<property name="dependencyService" ref="dependencyService" />
</bean>
<bean id="dependencyService" class="DependencyServiceImpl" />
</beans>
在 JavaConfig 中则是这样的:
@Configuration
public class MockConfiguration {
@Bean
public MockService mockService() {
return new MockServiceImpl(dependencyService());
}
@Bean
public DependencyService dependencyService() {
return new DependencyServiceImpl();
}
}
ComponentScan
对应的XML配置形式中的 <context:component-scan> 元素,配合一些注解,将注解定义的bean方法spring的IoC容器中。
可以通过basePackages等属性细粒度的定制扫描范围,如果不指定,默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描
@PropertySource
@PropertySource用于从某些地方加载*.proertise文件内容,并将其中的属性添加到IOC容器中。
@Configuration
@PropertySource("classpath:1.properties")
@PropertySource("classpath:2.properties")
@PropertySource("...")
public class XConfiguration{
...
}
在低于java8中,声明多个@PropertySource需要借助@PropertySources
@EnableAutoConfiguration
各种名字为 @Enable 开头的 Annotation,都是借助 @Import 的支持,收集和注册特定场景相关的 bean 定义
@Import
在XML形式的配置中,通过 <import resource=“XXX.xml”/> 的形式将多个分开的容器配置合到一个配置中
在JavaConfig形式中
@Configuration
@Import(MockConfiguration.class)
public class XConfiguration {
...
}
SpringApplication 执行流程
-
首先需要创建一个 SpringApplication 对象实例,然后调用这个创建好的 SpringApplication 的实例 run方法。
初始化之前要做的事:- 根据 classpath 里面是否存在某个特征类(org.springframework.web.context.ConfigurableWebApplicationContext)来决定是否应该创建一个为 Web 应用使用的 ApplicationContext 类型,还是应该创建一个标准 Standalone 应用使用的 ApplicationContext 类型。
- 使用 SpringFactoriesLoader 在应用的 classpath 中查找并加载所有可用的 ApplicationContextInitializer
- 使用 SpringFactoriesLoader 在应用的 classpath 中查找并加载所有可用的 ApplicationListener
- 推断并设置 main 方法的定义类。
-
执行 run 方法,首先遍历所有通过SpringFactoriesLoader 可以查找到并加载的SpringApplicationRunListener,调用他们的started()方法。
-
创建并配置当前SpringBoot应用程序将要使用的Environment(包括配置要使用的 PropertySource 以及 Profile)
-
遍历所有SpringApplicationRunListener 的 environmentPrepared()的方法,告诉它们:“当前 SpringBoot 应用使用的 Environment 准备好咯!”。
-
根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前 SpringBoot 应用创建什么类型的 ApplicationContext 并创建完成,然后根据条件决定是否添加 ShutdownHook,决定是否使用自定义的 BeanNameGenerator,决定是否使用自定义的 ResourceLoader,当然,最重要的,将之前准备好的 Environment 设置给创建好的 ApplicationContext 使用
-
ApplicationContext 创建好之后,SpringApplication 会再次借助 SpringFactoriesLoader,查找并加载 classpath 中所有可用的 ApplicationContextInitializer,然后遍历调用这些 ApplicationContextInitializer 的 initialize(applicationContext)方法来对已经创建好的 ApplicationContext 进行进一步的处理。
-
遍历调用所有 SpringApplicationRunListener 的 contextPrepared()方法,通知它们:“SpringBoot 应用使用的 ApplicationContext 准备好啦!”
-
最核心的一步,将之前通过 @EnableAutoConfiguration 获取的所有配置以及其他形式的 IoC 容器配置加载到已经准备完毕的 ApplicationContext。
-
遍历调用所有 SpringApplicationRunListener 的 contextLoaded() 方法,告知所有 SpringApplicationRunListener,ApplicationContext “装填完毕”!
-
调用 ApplicationContext 的 refresh() 方法,完成 IoC 容器可用的最后一道工序。
-
查找当前 ApplicationContext 中是否注册有 CommandLineRunner,如果有,则遍历执行它们。
-
正常情况下,遍历执行 SpringApplicationRunListener 的 finished() 方法,告知它们:“搞定!”。
应用日志和spring-boot-starter-logging
maven 依赖中添加 spring-boot-starter-logging
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-logging </artifactId>
</dependency>
将 spring-boot-starter-logging 作为依赖加入到当前应用的 classpath,就可以直接使用。如果需要对默认SpringBoot提供的应用日志做调整,可以通过几种方式进行配置:
-
遵循 logback 的约定,在 classpath 中使用自己定制的 logback.xml 配置文件。
-
在文件系统中任何一个位置提供自己的 logback.xml 配置文件,然后通过 logging.config 配置项指向这个配置文件来启用它,比如在 application.properties 中指定如下的配置。
logging.config=/{some.path.you.defined}/any-logfile-name-I-like.log
//按照默认的名称spring.log,生成到指定路径及日志。
logging.path=output/logs
//不指定的情况下默认生成在项目根目录,按照配置生成所需的日志名称
logging.file=D:/ooodin.log
//都不设置的话,不生成日志
快速 Web 应用开发与 spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
项目结构层面的约定
静态文件和页面模板统一放在 src/main/resources 相应子目录下:
src/main/resources/static 用于存放各类静态资源,比如 css,js 等。
src/main/resources/templates 用于存放模板文件,比如 *.vm。
spring-boot-starter-web 默认将为我们自动配置如下一些 SpringMVC 必要组件:
必要的 ViewResolver,比如 ContentNegotiatingViewResolver 和 Bean-NameViewResolver。
将必要的 Converter、GenericConverter 和 Formatter 等 bean 注册到 IoC 容器。
添加一系列的 HttpMessageConverter 以便支持对 Web 请求和相应的类型转换。
自动配置和注册 MessageCodesResolver。
其他。
spring-boot-starter-jdbc与数据访问
默认情况下,如果我们没有配置任何 DataSource,那么,SpringBoot 会为我们自动配置一个基于嵌入式数据库的 DataSource,这种自动配置行为其实很适合于测试场景,但对实际的开发帮助不大,基本上我们会自己配置一个 DataSource 实例,或者通过自动配置模块提供的配置参数对 DataSource 实例进行自定义的配置
假设我们的 SpringBoot 应用只依赖一个数据库,那么,使用 DataSource 自动配置模块提供的配置参数是最方便的:
- spring.datasource.url=jdbc:mysql://{database host}:3306/{databaseName}
- spring.datasource.username={database username}
- spring.datasource.password={database password}
spring-boot-starter-aop及其使用场景说明
只要引入 Spring 框架中 AOP 的相应依赖就可以直接使用 Spring 的 AOP 支持了
但是SpringBoot也提供有spring-boot-starter-aop 自动配置模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- @Aspect 表明是一个切面类
- @Component 将当前类注入到Spring容器内
- @Pointcut 切入点,其中execution用于使用切面的连接点。使用方法:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选)) ,可以使用通配符匹配字符,*可以匹配任意字符。
- @Before 在方法前执行
- @After 在方法后执行
- @AfterReturning 在方法执行后返回一个结果后执行
- @AfterThrowing 在方法执行过程中抛出异常的时候执行
- @Around 环绕通知,就是可以在执行前后都使用,这个方法参数必须为ProceedingJoinPoint,proceed()方法就是被切面的方法,上面四个方法可以使用JoinPoint,JoinPoint包含了类名,被切面的方法名,参数等信息。
SpringBoot项目简单介绍
SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
热部署
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
因为Intellij IEDA默认情况下不会自动编译,需要对IDEA进
行自动编译的设置,如下:
Shift+Ctrl+Alt+/,选择Registry
SpringBoot配置文件
SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件
yml配置文件的语法
-
配置普通数据。语法:
key: valuename: haohao
注意:value之前有一个空格
-
配置对象数据。语法:
key:
key1: value1
key2: value2
或者:
key: {key1: value1,key2: value2}person:
name: haohao
age: 31
addr: beijing
#或者
person: {name: haohao,age: 31,addr: beijing}注意:key1前面的空格个数不限定,在yml语法中,相同缩进代表同一个级别
-
配置Map数据
和配置对象写法相同 -
配置数组(List、Set)数据。语法:
key:
- value1
- value2
或者:
key: [value1,value2]city:
- beijing
- tianjin
- shanghai
- chongqing
#或者
city: [beijing,tianjin,shanghai,chongqing]
#集合中的元素是对象形式
student:
- name: zhangsan
age: 18
score: 100
- name: lisi
age: 28
score: 88
- name: wangwu
age: 38
score: 90注意:value与之前的 - 之间存在一个空格
使用注解@Value映射
@Controller
public class QuickStartController {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "springboot 访问成功! name="+name+",age="+age;
}
}
通过注解@ConfigurationProperties(prefix=“配置文件中的key的前缀”)可以将配置文件中的配置自动与实体进行映射
@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {
private String name;
private Integer age;
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "springboot 访问成功! name="+name+",age="+age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
使用@ConfigurationProperties方式可以进行配置文件与实体字段的自动映射,但需要字段必须提供set方法才可以,而使用@Value注解修饰的字段不需要提供set方法
SpringBoot整合Mybatis
- 添加Mybatis的起步依赖
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
- 添加数据库驱动坐标
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 添加数据库连接信息
在application.properties中添加数据量的连接信息
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?
useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
- 创建user表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三');
INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
- 创建实体Bean
public class User {
// 主键
private Long id;
// 用户名
private String username;
// 密码
private String password;
// 姓名
private String name;
//getter和setter方法 .. ..
}
- 编写Mapper
@Mapper
public interface UserMapper {
public List<User> queryUserList();
}
注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
- 配置Mapper映射文件
在src\main\resources\mapper路径下加入UserMapper.xml配置文件"
<?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.itheima.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>
- 在application.properties中添加mybatis的信息
#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=com.itheima.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
- 编写测试Controller
@Controller
public class MapperController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/queryUser")
@ResponseBody
public List<User> queryUser(){
List<User> users = userMapper.queryUserList();
return users;
}
}
- 测试
SpringBoot整合Junit
- 添加Junit的起步依赖
<!--测试的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void test() {
List<User> users = userMapper.queryUserList();
System.out.println(users);
}
}
SpringRunner继承自SpringJUnit4ClassRunner,使用哪一个Spring提供的测试测试引擎都可以
public final class SpringRunner extends SpringJUnit4ClassRunner
@SpringBootTest的属性指定的是引导类的字节码对象
- 控制台打印信息
SpringBoot整合Spring Data JPA
- 添加Spring Data JPA的起步依赖
<!-- springBoot JPA的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 添加数据库驱动依赖
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 在application.properties中配置数据库和jpa的相关属性
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?
useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
- 创建实体配置实体
@Entity
public class User {
// 主键
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 用户名
private String username;
// 密码
private String password;
// 姓名
private String name;
//setter和getter方法... ...
}
- 编写UserRepository
public interface UserRepository extends JpaRepository<User,Long>{
public List<User> findAll();
}
- 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MySpringBootApplication.class)
public class JpaTest {
@Autowired
private UserRepository userRepository;
@Test
public void test(){
List<User> users = userRepository.findAll();
System.out.println(users);
}
}
- 控制台打印信息
SpringBoot整合Redis
- 添加redis的起步依赖
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置redis的连接信息
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
- 注入RedisTemplate测试redis操作
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {
@Autowired
private UserRepository userRepository;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void test() throws JsonProcessingException {
//从redis缓存中获得指定的数据
String userListData = redisTemplate.boundValueOps("user.findAll").get();
//如果redis中没有数据的话
if(null==userListData){
//查询数据库获得数据
List<User> all = userRepository.findAll();
//转换成json格式字符串
ObjectMapper om = new ObjectMapper();
userListData = om.writeValueAsString(all);
//将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
redisTemplate.boundValueOps("user.findAll").set(userListData);
System.out.println("===============从数据库获得数据===============");
}else{
System.out.println("===============从redis缓存中获得数据===============");
}
System.out.println(userListData);
}
}