一.SpringBoot介绍
1.SpringBoot基本概念
Spring Boot是其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。
一.Spring回顾
加载xml配置,获取容器,获取MyBean (ClassPathXmlApplicationContext)
二.Spring的注解配置
一.Anno配置IOC
1.创建Spring的配置类
/**
* Spring的配置类 相当于是:applicationContext.xml
* @Configuration :Spring的配置标签,标记改类是Spring的配置类
*/
@Configuration
public class ApplicationConfig {
}
2.在配置类中定义Bean
/**
* Spring的配置类 相当于是:applicationContext.xml
* @Configuration :Spring的配置标签,标记改类是Spring的配置类
*/
@Configuration
public class ApplicationConfig {
/**
* @Bean : Spring的bean的定义标签 ,标记方法返回的对象交给Spring容器管理
*/
@Bean
public MyBean myBean(){
return new MyBean();
}
}
3.测试
加载配置类,获取容器,获取MyBean
@Test
public void test(){
//加载配置文件,拿到Spring容器
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class);
//通过容器获取Mybaean
MyBean bean = applicationContext.getBean(MyBean.class);
System.out.println(bean);
}
二.ComponentScan&ComponentScans自动扫描
1.准备MyBean帖@Component
@Component
public class MyBean {
}
2.创建配置类,帖@ComponentScan
@Configuration
//@ComponentScans
@ComponentScan("包名")
public class ApplicationConfig {
}
ComponentScan是ioc组件自动扫描,相当于是 context:component-scan base-package=*
默认扫描当前包,及其子包 ;
ComponentScan.lazyInit :懒初始化
ComponentScan.excludeFilters :排除
注意:如果使用了自动扫描 ,那么配置类中就不要去配置@Bean
3.bean的详解
- bean的id: 方法名
- bean的name:可以通过 @Bean标签的name属性指定
- 生命周期方法:initMethod , destroyMethod
- 单利多利: @Scope(“prototype”)
- 懒初始化: @Lazy
@Bean(name="" , initMethod ="" ,destroyMethod="" )
//@Scope("prototype")
//@Lazy
public MyBean myBean(){
return new MyBean();
}
三.依赖注入
1.手动定义bean的方式
直接通过调方法的方式注入bean,或者通过参数注入bean
2.自动扫描定义bean的方式
使用 @Autowired 注入
/**
* @Bean : Spring的bean的定义标签 ,标记方法返回的对象交给Spring容器管理
* bean的id: 方法名 myBean
* bean的name:可以通过 @Bean标签的name属性指定
* 生命周期方法:initMethod , destroyMethod
* 单利多利: @Scope("prototype")
*/
@Bean(initMethod = "init" , destroyMethod = "destroy")
public MyBean myBean(OtherBean otherBean){
MyBean myBean = new MyBean();
myBean.setName("娃娃");
//myBean.setOtherBean(otherBean());
myBean.setOtherBean(otherBean);
return myBean ;
}
@Bean
//@Lazy
public OtherBean otherBean(){
return new OtherBean();
}
四.条件Conditional
Conditional注解帖在bean的定义方法上来判断,如果不满足条件就不会定义bean
1.在Bean的定义方法帖@Conditional
@Bean
@Conditional(value = MyCondition.class)
public MyBean windowsMyBean(){
return new MyBean("windowMyBean");
}
@Bean
@Conditional(value = LinuxCondition.class)
public MyBean linuxMyBean(){
return new MyBean("linuxMyBean");
}
2.定义条件类
public class MyCondition implements Condition {
/**
* 匹配方法,返回值决定是否满足条件
*/
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//获取系统环境
String systemName = context.getEnvironment().getProperty("os.name");
if("Windows 10".equals(systemName)){
return true;
}
return false;
}
}
五.@Import
1.直接导入Bean或者配置类
@Configuration
@Import(ApplicationOtherConfig.class) //导入其他的配置类
public class ApplicationConfig
2.导入ImportSelector
定义ImportSelector
public class MyImportSelector implements ImportSelector {
//选择导入,该方法返回我们需要导入的类的全限定名
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{
"cn.itsource._07_import_selector.MyBean",
"cn.itsource._07_import_selector.OtherBean"};
}
}
@Configuration
@Import(MyImportSelector.class) //导入选择器
public class ApplicationConfig
3.导入ImportBeanDefinitionRegistrar
定义 ImportBeanDefinitionRegistrar
public class MyBeanRegistor implements ImportBeanDefinitionRegistrar {
//注册bean , BeanDefinitionRegistry :注册bean的注册器
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//参数:beanName :bean的名字
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(MyBean.class);
registry.registerBeanDefinition("myBean",rootBeanDefinition );
}
}
@Configuration
@Import(MyBeanRegistor.class) //导入bean注册器
public class ApplicationConfig
六.FactoryBean
通过工厂定义bean
1.定义FactoryBean
public class MyBeanFactoryBean implements FactoryBean<MyBean> {
public MyBean getObject() throws Exception {
return new MyBean();
}
public Class<?> getObjectType() {
return MyBean.class;
}
public boolean isSingleton() {
return true;
}
}
2.配置 MyBeanFactoryBean的bean定义
@Configuration
public class ApplicationConfig {
@Bean
public MyBeanFactoryBean myBean(){
return new MyBeanFactoryBean();
}
}
3.测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes ={ ApplicationConfig.class})
public class AnnoTest {
@Autowired
private MyBean myBean;
@Test
public void test(){
System.out.println(myBean);
}
}
七.Bean生命周期
1.Bean+InitMethod+DestoryMethod
@Bean(InitMethod="" , DestoryMethod="")
2.InitializingBean, DisposableBean
public class MyBean implements InitializingBean, DisposableBean {
public MyBean(){
System.out.println("创建.............");
}
public void destroy() throws Exception {
System.out.println("destroy方法...........");
}
public void afterPropertiesSet() throws Exception {
System.out.println("初始化方法...........");
}
}
3.PostConstruct+PreDestroy
@Component
public class MyBean {
@PostConstruct
public void init(){
System.out.println("init.....");
}
@PreDestroy
public void destory(){
System.out.println("destory.....");
}
}
4.BeanPostProcessor后置处理器
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之前.....:"+bean);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之后.....:"+bean);
return bean;
}
}
三.SpringBoot-HelloWorld
一.HelloWorld
1.HelloWorld-web应用
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.创建配置类
@SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class);
}
}
3.编写Controller
@Controller
public class Example {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
}
二.HelloWorld-web应用分析
1.疑惑的点分析
-
spring-boot-starter-parent :SpringBoot的父工程,帮我们管理了很多的基础jar包
-
spring-boot-starter-web :SpringBoot和SpringMvc整合的jar包,并且导入了日志,tomcat,等等相关的jar包
-
RestController : Controller+ResponseBody
-
@EnableAutoConfiguration : 开启自动配置功能
-
SpringApplication.run : 启动SpringBoot应用
-
jar :SpringBoot应用默认打jar包
-
SpringBootApplication:包括三个标签组成
@SpringBootConfiguration - @Configuration : Spring的配置标签
@EnableAutoConfiguration :开启自动配置
@ComponentScan :组件自动扫描
dependencyManagement
该标签下的jar包,默认是不能被子项目直接使用的 , 他只有声明的功能 , 如果只项目想用这里标签里面的jar包 ,需要显示的写出来 ,而版本号使用父工程的。达到版本号统一管理的效果
dependencies
这个标签下面的jar包默认会被子项目直接继承直接使用
2.SpringBoot自动配置分析
@EnableAutoConfiguration开启自动配置功能 ,
@EnableAutoConfiguration ->
AutoConfigurationImportSelector ->
spring-boot-autoconfigure-2.0.5.RELEASE.jar ->
spring.factories - EnableAutoConfiguration ->
在程序启动的过程中,加载 EnableAutoConfiguration 节点下的自动配置的类,完成相关的自动配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fJTBmpCG-1581429627008)(SpringBoot.assets/1568527822807.png)]
四.SpringBoot的特点
1.使用注解配置,无需xml(简单粗暴)
2.快速搭建,开发
3.简化的maven
4.方便的和三方框架集成
5.内嵌tomcat,部署简单
6.内置健康检查,监控等
7.自动配置,让配置更加简单
五.SpringBoot基本使用
一.项目结构
src
--main
--java
--resources
--static //静态资源目录
--templates //模板页面目录,如:jsp ,ftl
--application.properties/application.yml //默认配置文件
二.独立运行
1.导入打包插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.打包
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PeGJtGP8-1581429627009)(SpringBoot.assets/1568515028409.png)]
打包命令会把jar打包到target目录
3.运行
java -jar xxx.jar
三.热部署
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
2.编译代码
ctrl + F9
3.配置IDEA的自动编译功能
配置setting的自动编译
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Q4umjG0v-1581429627010)(SpringBoot.assets/1568515414056.png)]
按 ctrl +shift + alt + / -> registry -> 如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZcAutSSf-1581429627010)(SpringBoot.assets/1568515493870.png)]
四.yml基本语法
多个级之间用:分类,并且换行缩进 , 值不用换行 , 值前面有个空格
五.SpringBoot读取配置
一.使用@Value标签
配置文件
user:
username: ls
password: 456
age: 99
绑定配置的对象
@Component
public class User {
//@Value :从配置文件中取值 SPEL
@Value("${user.username}")
private String username = "zs";
@Value("${user.password}")
private String password = "123";
@Value("${user.age}")
private int age = 18;
. . . . . .
二.使用@ConfigurationProperties
配置文件
employee:
username: ls
password: 456
age: 99
绑定配置的对象
@Component
@ConfigurationProperties(prefix = "employee")
public class Employee {
private String username = "zs";
private String password = "123";
private int age = 18;
@ConfigurationProperties : 自动的根据前缀从配置中过滤出配置项目,然后根据当前对象的列名进行匹配,自动赋值
六.多环境配置切换
1.方式一
spring:
profiles:
active: test #激活(选择)环境test
---
spring:
profiles: dev #指定环境名字dev
server:
port: 9999
---
spring:
profiles: test #指定环境名字test
server:
port: 8888
2.方式二
通过配置文件的名字来识别环境
application-dev.yml
server:
port: 9999
application-test.yml
server:
port: 8888
application.yml
spring:
profiles:
active: test
#根据文件名字配置 application-dev.properties
七.日志的使用
1.基本使用
private Logger logger = LoggerFactory.getLogger(MySpringBootTest.class);
...
logger.error("我是一个error日志.....");
logger.warn("我是一个warn日志.....");
logger.info("我是一个info日志.....");
logger.debug("我是一个debug日志.....");
logger.trace("我是一个trace日志.....");
2.配置日志
#logging.level.cn.itsource=error
#logging.file=my.txt
#logging.file.max-size=1KB
#logging.pattern.console="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
3.指定配置文件配置logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 定义常量 : 日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n"/>
<!--ConsoleAppender 用于在屏幕上输出日志-->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<!--定义控制台输出格式-->
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--打印到文件-->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/springboot.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>logs/springboot-%d{yyyyMMdd}-%i.log.gz</fileNamePattern>
<maxFileSize>1KB</maxFileSize>
<maxHistory>30</maxHistory>
<!--总上限大小-->
<totalSizeCap>5GB</totalSizeCap>
</rollingPolicy>
<!--定义控制台输出格式-->
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--root是默认的logger 这里设定输出级别是debug-->
<root level="info">
<!--定义了两个appender,日志会通过往这两个appender里面写-->
<appender-ref ref="stdout"/>
<appender-ref ref="file"/>
</root>
<!--如果没有设置 additivity="false" ,就会导致一条日志在控制台输出两次的情况-->
<!--additivity表示要不要使用rootLogger配置的appender进行输出-->
<logger name="cn.itsource" level="error" additivity="false">
<appender-ref ref="stdout"/>
<appender-ref ref="file"/>
</logger>
</configuration>
八.SpringBoot集成Thymeleaf
1.模板引擎的原理
2.jsp的原理
集成Thymeleaf
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.创建模板 resources/templates/hello.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!--使用语法th:text 将div里面的文本内容设置为 -->
<div th:text="${msg}">这是显示欢迎信息</div>
</body>
</html>
3.编写controller
@Controller
public class HelloController {
@RequestMapping("/index")
public String hello(Model model){
model.addAttribute("msg","后面有人,认真听课" );
return "hello";
}
}
4.编写主配置类
5.Thymeleaf的自动配置原理
@EnableAutoConfiguration 开启自动配置功能,通过一个AutoConfigurationImportSelector导入选择器去扫描 spring-boot-autoconfigure-2.0.5.RELEASE.jar 自动配置包下面的 spring.factories 文件中的很多很多的自动配置的类
而:ThymeleafAutoConfiguration 是的Thymeleaf的自动配置 ,在这个自动配置类里面通过一个ThymeleafProperties去读取配置文件中的配置(也有默认配置) ,来自动配置Thymeleaf,比如Thymeleaf的视图解析器的自动配置如下:
@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
...
return resolver;
}
6.Thymeleaf的语法
下去找时间看
九.静态资源
1.静态资源目录
resource/static
2.webjars
导入jquery依赖 ( http://www.webjars.org/)
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
导入jquery的js
<script src="/webjars/jquery/3.4.1/jquery.js"></script>
3.首页
resources/index.html
4.图标
resources/favicon.ico
2019年9月15日
今天作业
1.全天代码 - 做不完的死定了
今天重点
1.SpringBoot - helloworld分析
2.SpringBoot 自动配置原理
3.@Value+@ConfigurationProperties 参数读取
4.打包运行
5.thymeleaf集成
2019年9月14日
今天作业
1.全天代码
2.编码规范
包名全小写 ,多个单词用_分开; 类名首字母大写,驼峰 ; 方法名首字母小写,驼峰
3.补全课堂笔记
今天重点
1.Spring注解配置
(重点)_02_anno_ioc
(重点)_03_anno_scan
_04_bean_detail
_05_condition
(重点)_06_import
_07_import_selector
_08_improt_registry
_09_factorybean
_10_initializingbean_disposablebean
_11_postconstract_predestory
_12_beanpostprocessor