视频链接:https://www.bilibili.com/video/BV1XQ4y1m7ex/?vd_source=9545770e4a2968c05878ffac8589ec6c
视频选集:P1— P29
文章目录
1.springboot简介
- 因为Spring , SpringMVC需要使用的大量的配置文件( xml文件)还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象需要了解其他框架配置规则。
- SpringBoot就相当于不需要配置文件的Spring+SpringMVC。常用的框架和第三方库都已经配置好了。拿来就可以使用了。
- SpringBoot开发效率高,使用方便多了
1.1 JavaConfig
JavaConfig:使用java类作为xml配置文件的替代,是配置spring容器的纯java的方式。在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器)
使用两个注解:
1 ) @configuration:放在一个类的上面,表示这个类是作为配置文件使用的。
2 ) @Bean:声明对象,把对象注入到容器中。
1.2 使用xml文件配置容器
先在IDEA中创建空的项目:
然后创建maven项目,并在pom.xml中配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjpowernode</groupId>
<artifactId>001-springboot-pre</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
注意:刷新按钮,将自动下载配置
定义实体类:
package com.bjpowernode.vo;
public class Student {
private String name;
private Integer age;
private String sex;
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
定义xml文件:
测试:
package com.bjpowernode;
import com.bjpowernode.vo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
/**
* 使用xml作为容器配置文件
*/
@Test
public void test01(){
String config = "beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
Student student = (Student) ctx.getBean("myStudent");
System.out.println("容器中的对象:" + student);
}
}
运行效果为:
1.3 使用JavaConfig配置容器
创建springConfig文件:
package com.bjpowernode.vo.config;
import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration:表示当前类是作为配置文件使用的,就是用来配置容器的
* 位置:在类的上面
*
* Configuration这个类就相当于beans.xml
*/
@Configuration
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象,在方法的上面加入@Bean
* 方法的返回值对象就注入到容器中
*
* @Bean:把dioxin这几日搭配spring容器中,作用相当于<bean>
* 位置:方法的上面
*
* 说明:@Bean ,不指定对象的名称,默认是方法名是id
*/
@Bean
public Student createStudent(){
Student s1 = new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
/**
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@Bean(name = "lisistudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
测试:
package com.bjpowernode;
import com.bjpowernode.vo.Student;
import com.bjpowernode.vo.config.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
/**
* 使用javaConfig
*/
@Test
public void test02(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Student student = (Student) ctx.getBean("createStudent");
System.out.println("使用JavaConfig创建的bean对象"+student);
}
@Test
public void test03(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Student student = (Student) ctx.getBean("lisistudent");
System.out.println("使用JavaConfig创建的bean对象"+student);
}
}
1.4 导入xml配置文件@ImportResource
@ImportResource是导入xml配置,等同于xml文件的resources
先重新定义一个猫的类:
package com.bjpowernode.vo.vo;
public class Cat {
private String cardId;
private String name;
private Integer age;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
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 "Cat{" +
"cardId='" + cardId + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
为猫重新定义一个配置类:
在SpringConfig中导入为猫定义的配置类:
测试:
package com.bjpowernode;
import com.bjpowernode.vo.vo.Cat;
import com.bjpowernode.vo.vo.Student;
import com.bjpowernode.vo.config.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test04(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Cat student = (Cat) ctx.getBean("myCat");//调用SpringConfig类中,但同样能访问myCat
System.out.println("使用JavaConfig创建的bean对象"+student);
}
}
1.5 读取属性配置文件@ PropertySource
@PropertyResource:读取properties属性配置文件。使用属性配置文件可以实现外部化配置,在程序代码之外提供数据。
步骤︰
1.在resources目录下,创建properties文件,使用k=v的格式提供数据
2.在PropertySource指定properties文件的位置
3.使用@value ( value="${key}”)
第一步:先创建properties文件
第二步:PropertySource指定properties文件的位置
package com.bjpowernode.vo.config;
import com.bjpowernode.vo.vo.Student;
import org.springframework.context.annotation.*;
/**
* Configuration:表示当前类是作为配置文件使用的,就是用来配置容器的
* 位置:在类的上面
*
* Configuration这个类就相当于beans.xml
*/
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
@PropertySource(value = "classpath:config.properties")//重点
@ComponentScan(basePackages = "com.bjpowernode.vo.vo")
public class SpringConfig {
@Bean
public Student createStudent(){
Student s1 = new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
/**
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean的name属性,指定对象的名称(id)
*/
@Bean(name = "lisistudent")
public Student makeStudent(){
Student s2 = new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
第三步:使用@value
package com.bjpowernode.vo.vo;
import org.junit.validator.ValidateWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("tiger")
public class Tiger {
@Value("${tiger.name}")
private String name;
@Value("${tiger.age}")
private Integer age;
@Override
public String toString() {
return "Tiger{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试:
package com.bjpowernode;
import com.bjpowernode.vo.vo.Cat;
import com.bjpowernode.vo.vo.Student;
import com.bjpowernode.vo.config.SpringConfig;
import com.bjpowernode.vo.vo.Tiger;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test05(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Tiger tiger = (Tiger) ctx.getBean("tiger");
System.out.println("tiger=="+tiger);
}
}
效果:
注意:
以前写在.xml文件中:
现在写在SpringConfig中:
1.6 SpringBoot特性
SpringBoot是Spring中的一个成员,可以简化Spring ,SpringMVC的使用。他的核心还是IOC容器。
特点:
- 创建spring应用
- 内嵌的tomcat , jetty , Undertow
- 提供了starter起步依赖,简化应用的配置。【比如使用MyBatis框架,需要在Spring项目中,配置MyBatis的对象SqlSessionFactory ,Dao的代理对象在SpringBoot项目中,在pom.xml里面,加入一个mybatis-spring-boot-starter依赖】
- 尽可能去配置spring和第三方库。叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中,开发人员可以直接使用)
- 提供了健康检查,统计,外部化配置
- 不用生成代码,不用使用xml,做配置
2.创建springboot项目
2.1 第一种方式
使用Spring提供的初始化器,就是向导创建SpringBoot应用
然后选择javaweb
下面为目录文件:
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--SpringBoot的父项目-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/>
</parent>
<!--当前项目的gav【坐标】-->
<groupId>com.bjpowernode</groupId>
<artifactId>springboot_first</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 第二种方式
使用自定义的地址
注:无论是第一种还是第二种都需要联网
2.3 第三种方式 使用maven向导创建项目
在pom.xml中添加:
同时在resources中添加:
那么这个项目就和springboot一样了
3.基于springboot的web例子
创建项目
选择web项目,然后将不需要的进行删除。
定义controller:
直接运行application:
测试:
4. @SpringBootApplication注解
复合注解
package org.springframework.boot.autoconfigure;
import java.lang.annotation.*;
import org.springframework.*;
@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 {
@AliasFor(
annotation = EnableAutoConfiguration.class
)
Class<?>[] exclude() default {};
@AliasFor(
annotation = EnableAutoConfiguration.class
)
String[] excludeName() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackages"
)
String[] scanBasePackages() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackageClasses"
)
Class<?>[] scanBasePackageClasses() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "nameGenerator"
)
Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
其中:
最核心的是这三个注解
@SpringBootConfiguration //1. 当作配置文件用
@EnableAutoConfiguration //2. 启动自动配置功能,把常见的框架,第三方对象都创建好,方便使用
@ComponentScan //3. 扫描到程序中所有的注解,进一步创建对象,将对象放在容器中
4.1 @SpringBootConfiguration
使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,可以使用Bean声明对象,注入到容器
4.2 @EnableAutoConfiguration
启用自动配置,把java对象配置好,注入到spring容器中。例如可以把mybatis的对象创建好,放入到容器中
4.3 @ComponentScan
扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等
默认扫描的包:@ComponentScan所在的类所在的包和子包。
5.springboot核心配置文件
配置文件名称: application
扩展名有: properties( k=v) ; yml ( k: v)
使用application.properties,application.yml
创建新的项目,定义controller:
将原来的application,自定义,并运行:
进行测试访问:
5.1 properties配置文件
启动myapplication:
测试:
5.2 yml配置文件
yml 是一种 yaml 格式的配置文件,主要采用一定的空格、换行等格式排版进行配置。yaml是一种直观的能够被计算机识别的的数据序列化格式,容易被人类阅读,yaml类似于xml,但是语法比 xml简洁很多,值与前面的冒号配置项必须要有一个空格,yml缀也可以使用yaml后缀
注意:当两种格式配置文件同时存在﹐在SpringBoot2.4开始,使用的是yml配置文件.修改配置名称都为application。
重新运行Application ,查看启动的端口及上下文根
注意:当有properties和yml的时候,默认使用properties格式的配置文件
5.3 多环境配置
在实际开发的过程中,我们的项目会经历很多的阶段(开发->测试->上线),每个阶段的配置也会不同,例如:端口、上下文根、数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot提供了多环境配置,具体步骤如下
项目名称: 006-springboot-multi-environment
为每个环境创建一个配置文件,命名必须以 application-环境标识. properties | yml
有开发环境,测试环境,上线的环境。
每个环境有不同的配置信息,例如端口,上下文件,数据库url,用户名,密码等等
使用多环境配置文件,可以方便的切换不同的配置。
比如:
创建开发环境的配置文件: application-dev.properties( application-dev.yml )
创建测试者使用的配置: application-test.properties
在application-properties中定义启动哪一个:
将启动配置文件的类型从properties改为yml:
5.4 springboot自定义配置
SpringBoot 的核心配置文件中,除了使用内置的配置项之外,我们还可以在自定义配置,然后采用如下注解去读取配置的属性值
5.4.1 @Value
controller类:
运行MyApplication:
测试:
5.4.2 @ConfigurationProperties
将整个文件映射成一个对象,用于自定义配置项比较多的情况
package com.bjpowernode.vo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component //创建此类的对象
@ConfigurationProperties(prefix = "school")//在配置文件中找school开头的属性
public class SchoolInfo {
//属性名和properties中的一致
private String name;
private String website;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "SchoolInfo{" +
"name='" + name + '\'' +
", website='" + website + '\'' +
", address='" + address + '\'' +
'}';
}
}
controller:
package com.bjpowernode.controller;
import com.bjpowernode.vo.SchoolInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class BootController {
@Resource //自动注入
private SchoolInfo info;
@RequestMapping("/info")
@ResponseBody
public String queryInfo(){
return "SchoolIfo对象 ==" + info.toString();
}
}
然后重新运行MyApplication文件
测试:
注意:
为了解决上面的问题:
只需要添加下面的代码:
6.springboot中使用JSP
6.1 步骤描述
SpringBoot不推荐使用jsp ,而是使用模板技术代替jsp
使用jsp需要配置:
-
加入一个处理jsp的依赖,负责编译jsp文件
-
如果需要使用servlet,jsp,jstl的功能
-
创建一个存放jsp的目录,一般叫做webapp
index.jsp -
需要在pom.xml指定jsp文件编译后的存放目录。
META-INF/resources -
创建Controller,访问jsp
-
在application.propertis文件中配置视图解析器
6.2 实现
添加依赖:
创建webapp文件夹:
编写index.jsp代码:
创建controller:
package com.bjpowernode.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class JspController {
// public String doJsp(HttpServletRequest request){
//
// request.setAttribute("data","SpringBoot使用Jsp");
// //视图的逻辑名称
// return "index";
// }
//效果和上面的一样
@RequestMapping("/myjsp")
public String doJsp(Model model){
//把数据放入到request作用域
model.addAttribute("data","SpringBoot使用Jsp");
//request.setAttribute("data","SpringBoot使用Jsp");
//视图的逻辑名称
return "index";
}
}
在properties文件中定义:
在pom.xml中添加配置:
<build>
<!--指定jsp编译后的存放目录-->
<resources>
<resource>
<!--jsp原来的目录-->
<directory>src/main/webapp</directory>
<!--指定编译后的存放目录-->
<targetPath>META-INF/resources</targetPath>
<!--指定处理的目录和文件-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
启动Application进行测试:
注意:如果出现Whitelabel Error Page,重启IDEA就行
7. springboot中使用ApplicationContext
在main方法中SpringApplication.run()方法获取返回的Spring容器对象,再获取业务bean进行调用.
创建Spring Boot项目:010-springboot-container指定项目的 gav和版本等信息
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
ConfigurableApplicationContext:接口,是ApplicationContext的子接口
public interface ConfigurableApplicationContext extends ApplicationContext
- 创建一个新的项目
- 定义接口
- 定义接口实现类
- 将主方法修改
- 运行测试
8. CommandLineRunner接口
开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot 给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner 和ApplicationRunner。他们的执行时机为容器启动完成的时候。这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于: ApplicationRunner中run方法的参数为ApplicationArguments ,而CommandLineRunner接口中 run方法的参数为String数组
这两个接口都有一个run方法。执行时间在容器对象创建好后,自动执行run ( )方法。
可以完成自定义的在容器对象创建好后的一些操作。
代码实现:
运行效果: