SpringBoot核心技术一

编程入门 行业动态 更新时间:2024-10-10 13:22:03

SpringBoot<a href=https://www.elefans.com/category/jswz/34/1767668.html style=核心技术一"/>

SpringBoot核心技术一

尚硅谷SpringBoot核心技术篇

01、SpringBoot_入门-课程简介

02、SpringBoot_入门-Spring Boot简介

(starter模块&)

03、SpringBoot_入门-微服务简介

(微服务与Spring Cloud &)

04、SpringBoot_入门-环境准备

(下载和安装Maven(settings.xml运行时指定profiles配置,告诉maven用JDK1.8来编译运行项目。启动IDEA时在settings配置文件中的Build构建工具绑定安装的Maven,并勾上Override)&)

05、SpringBoot_入门-springboot-helloworld

(@SpringBootApplication背后的秘密(启动自动导入Jar,导入springBoot的依赖 spring-boot-starter-parent,spring-boot-starter-web,通过@SpringBootApplication标注主程序类告诉是一个springBoot应用,传入主程序的class和args参数,启动spring应用,直接运行main方法启动程序。导入spring-boot-maven-plugin可以将应用打包成可执行的jar包,运行package进行打包处理,java -jar *.jar)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0"xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-01-helloworld</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><!-- 这个插件,可以将应用打包成一个可执行的jar包;--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

HelloController.java

package com;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello(){return "Hello World!";}
}

HelloWorldMainApplication.java

package com.atguigu;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/***  @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用*/
@SpringBootApplication
public class HelloWorldMainApplication {public static void main(String[] args) {// Spring应用启动起来SpringApplication.run(HelloWorldMainApplication.class,args);}
}
package com.atguigu.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class HelloController {//    @ResponseBody
//    @RequestMapping("/hello")
//    public String hello(){
//        return "Hello World!";
//    }
}

06、SpringBoot_入门-HelloWorld细节-场景启动器(starter)

(了解纷杂的spring—boot—starter(启动器,spring-boot-starter 导入了web模块正常运行所依赖的组件,版本springBoot会自动控制)&)

07、SpringBoot_入门-HelloWorld细节-自动配置

(理解@EnableAutoConfiguration(@EnableAutoConfiguration开启自动配置功能,)&使用import元素(给容器导入组件,)&)

08、SpringBoot_入门-使用向导快速创建Spring Boot应用

(使用 Spring Initializr(spring Initializr快速创建项目,Resource下的static文件夹保存所有的静态资源,templates保存所有的模块页面,application.properties保存spring Boot应用的配置文件,server.port=8081。Eclipse中使用Spring starter project创建spring BOOT

项目 )&@RestController注解的使用(返回的数据直接写给浏览器)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-01-helloworld-quick</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-01-helloworld-quick</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Spring Boot进行单元测试的模块--><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>

application.properties

server.port=8081
package com.atguigu.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot01HelloworldQuickApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot01HelloworldQuickApplication.class, args);}
}
package com.atguigu.springboot.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;//这个类的所有方法返回的数据直接写给浏览器,(如果是对象转为json数据)
/*@ResponseBody
@Controller*/
@RestController
public class HelloController {@RequestMapping("/hello")public String hello(){return "hello world quick!";}// RESTAPI的方式
}

09、SpringBoot_配置-yaml简介

(YAML配置(以数据为中心,更适合做配置文件,)&)

10、SpringBoot_配置-yaml语法

(开始一个新项目:三个示例中的Compose YAML(空格控制层级关系,空格一样在一个层级,大小写敏感,字符串默认不需要加引号,双引号不会转义字符串里面的特殊字符,单引号会进行转义只作为一个普通的字符串展示,对象还是键值对的方式,值和冒号中间一定要有空格。行内写法 friends:{lastName:zhangsan,age:19},数组或集合用-表示数组中的一个元素,行内写法pets:[cat,dog])&)

11、SpringBoot_配置-yaml配置文件值获取

(Spring Boot条件化自动装配(@ConfigurationProperties告诉springBoot将本类中的所有属性和配置文件中的相关配置进行绑定,)&注解配置(@Component)(配置文件处理器,spring-boot-configuration-processor,绑定配置文件会有提示,-与驼峰大写都可以)&)

12、SpringBoot_配置-properties配置文件编码问题

(ASCII编码查看器(Setting file encoding 设置文件编码,UTF-8->ASCII)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-02-config</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-02-config</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><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-configuration-processor</artifactId><optional>true</optional></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>

application.properties

server.port=8088

person.properties

person.last-name=\u674E\u56DB
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xsi:schemaLocation=" .xsd"><bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

application-prod.properties

#server.port=80

application-dev.properties

#server.port=8082

application.yml


server:port: 8081
spring:profiles:active: prod---
server:port: 8083
spring:profiles: dev---server:port: 8084
spring:profiles: prod

application.properties

server.port=8081
#spring.profiles.active=dev# idea\uFF0Cproperties\u914D\u7F6E\u6587\u4EF6utf-8
# \uFFFD\uFFFD\uFFFD\uFFFDperson\uFFFD\uFFFD\u05B5
person.last-name=\u5F20\u4E09${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
package com.atguigu.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;//@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot02ConfigApplication.class, args);}
}
package com.atguigu.springboot.service;public class HelloService {
}
package com.atguigu.springboot.controller;import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Value("${person.last-name}")private String name;@RequestMapping("/sayHello")public String sayHello(){return "Hello "+name;}}
package com.atguigu.springboot.config;import com.atguigu.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件** 在配置文件中用<bean><bean/>标签添加组件**/
@Configuration
public class MyAppConfig {//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名@Beanpublic HelloService helloService02(){System.out.println("配置类@Bean给容器中添加组件了...");return new HelloService();}}
package com.atguigu.springboot.bean;import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;import javax.validation.constraints.Null;
import java.util.Date;
import java.util.List;
import java.util.Map;/*** 将配置文件中配置的每一个属性的值,映射到这个组件中* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;*      prefix = "person":配置文件中哪个下面的所有属性进行一一映射** 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;*  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;**/
//@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {/*** <bean class="Person">*      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>* <bean/>*///lastName必须是邮箱格式// @Email//@Value("${person.last-name}")private String lastName;//@Value("#{11*2}")private Integer age;//@Value("true")private Boolean boss;private Date birth;//@Value("${person.maps}")private Map<String,Object> maps;private List<Object> lists;private Dog dog;@Overridepublic String toString() {return "Person{" +"lastName='" + lastName + '\'' +", age=" + age +", boss=" + boss +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getBoss() {return boss;}public void setBoss(Boolean boss) {this.boss = boss;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}
}
package com.atguigu.springboot.bean;public class Dog {private String name;private Integer age;@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + 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;}
}
package com.atguigu.springboot;import com.atguigu.springboot.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {@AutowiredPerson person;@AutowiredApplicationContext ioc;@Testpublic void testHelloService(){boolean b = ioc.containsBean("helloService02");System.out.println(b);}@Testpublic void contextLoads() {System.out.println(person);}}

13、SpringBoot_配置-@ConfigurationProperties与@Value区别

(使用@Resource和@Value配置依赖(@Value(“${person.last-name}”)获取配置文件中的信息,#{11*2}spel可以计算值)&松散索引扫描(@Value()只绑定简单的值,不支持复杂类型的绑定)&JSR303验证)

14、SpringBoot_配置-@PropertySource、@ImportResource、@Bean

(静态函数Object.getOwnPropertySymbols(..)(加载@PropertySource指定的properties配置文件,) &使用import语句导入模块(springBoot想让自己的spring配置文件生效,@ImportResource导入spring的配置文件,springBoot通过配置类给容器添加组件方式,推荐使用全注解的方式@Configuration,容器组件名字和方法名一致)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-02-config-02</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-02-config-02</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><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>

application.properties

server.port=8083
package com.atguigu.springboot02config02;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02Config02ApplicationTests {@Testpublic void contextLoads() {}}

application.properties

server.port=8081# 配置项目的访问路径
server.context-path=/boot02#spring.config.location=G:/application.properties
package com.atguigu.springboot02config02;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot02Config02Application {public static void main(String[] args) {SpringApplication.run(SpringBoot02Config02Application.class, args);}
}
package com.atguigu.springboot02config02.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/hello")public String hello(){return "hello";}
}

15、SpringBoot_配置-配置文件占位符

(带占位符的国际化信息(${random.value} 获取随机数,${random.int[1024,65536]})&)

16、SpringBoot_配置-Profile多环境支持

(环境与profile&激活profile(application-{profile}.yml动态配置环境,spring.profiles.active=dev,---三个横杠分成不同的文档块,program arguments --spring-profiles.active=dev,命令行方式 --spring.profiles.active=dev,虚拟机参数 VM options -Dspring.profiles.active=dev)&)

17、SpringBoot_配置-配置文件的加载位置

(配置文件管理(配置文件的位置,先加载file:./config/ 文件路径下(当前项目的根路径和src或者pom.xml同级),或者file:./文件路径下,classpath:/config/类路径config下或者直接放在类路径下(resource),高优先级会覆盖低优先级。互补配置server.context-path=/boot02配置项目的访问路径, spring.config.location来改变默认配置文件的位置)&)

18、SpringBoot_配置-外部配置加载顺序

(context-path导致监控失败(外部配置文件的加载顺序,命令行参数 jar --server.port=8087,jar包外的带application-${profile}.properties(jar包和properties配置文件在同一目录下),jar包内的,jar包外的application.properties,jar包内的,@Configuration注解上的@PropertySource,通过SpringApplication.setDefaultProperties指定的默认属性)&)

19、SpringBoot_配置-自动配置原理

(条件注解@Conditional&spring-boot-autoconfigure模块分析(springBoot启动时加载主配置类,开启自动配置功能@EnableAutoConfiguration,)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-02-config-autoconfig</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-02-config-autoconfig</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><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>
package com.atguigu.springboot;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigAutoconfigApplicationTests {@Testpublic void contextLoads() {}}

application.properties

# 开启SpringBoot的debug
debug=true
server.port=8080# 我们能配置的属性都是来源于这个功能的properties类
spring.http.encoding.enabled=true
spring.http.encoding.charset=utf-8
spring.http.encoding.force=true
package com.atguigu.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot02ConfigAutoconfigApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot02ConfigAutoconfigApplication.class, args);}
}

20、SpringBoot_配置-@Conditional&自动配置报告

(条件配置(@Conditional)(@Conditional后面有一个条件判断类,条件成立配置类里内容才会生效,或者才会给容器添加组件)&Conditional使用&Express实战:后端服务&Debugger(debug=true控制台打印自动配置报告,确定哪些类生效)&)

21、SpringBoot_日志-日志框架分类和选择

(Apache Commons Logging和SLF4J(LoggerFactory.getLogger())&)

22、SpringBoot_日志-slf4j使用原理

(Apache Commons Logging和SLF4J (通过适配器包装层,把commons-log转为其他对应的ja包,做为不同日志框架转为SLF4J的转环包。)&)

23、SpringBoot_日志-其他日志框架统一转换为slf4j

(Slf4j&)

24、SpringBoot_日志-SpringBoot日志关系

(选择日志框架(引入其他框架,把其他框架依赖的日志框架排除掉,不用再做任何的配置,springBoot就可以适配起来)&)

25、SpringBoot_日志-SpringBoot默认配置

(日志格式和类型(logger.trace(“”)跟踪日志,debug()调试信息,logger.info自定义信息,warn,error日志级别由低到高,logging.level=trace,logging.file=springBoot.log在当前项目下生产日志,logging.path在当前磁盘的根路径下生产文件)&)

26、SpringBoot_日志-指定日志文件和日志Profile功能

(输出格式化的日期和时间(如果使用Logback在类路径下使用logback-spring.xml或logback.xml,如果使用log4j,类路径下log4j2.xml,JDK的logging.properties)&)

27、SpringBoot_日志-切换日志框架

(用户自定义切换语言示例(排除log4j-over-slf4j不要把logging4j替换为slf4j,想要使用logg4j,面向slf4j编程,要用logging4j实现使用slf4j-log4j12,也可以直接引入spring-boot-starter-log4j2,二选一即可)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-03-logging</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring-boot-03-logging</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><artifactId>spring-boot-starter-logging</artifactId><groupId>org.springframework.boot</groupId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</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>
package com.atguigu.springboot;import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot03LoggingApplicationTests {//记录器Logger logger = LoggerFactory.getLogger(getClass());@Testpublic void contextLoads() {//System.out.println();//日志的级别;//由低到高   trace<debug<info<warn<error//可以调整输出的日志级别;日志就只会在这个级别以以后的高级别生效logger.trace("这是trace日志...");logger.debug("这是debug日志...");//SpringBoot默认给我们使用的是info级别的,没有指定级别的就用SpringBoot默认规定的级别;root级别logger.info("这是info日志...");logger.warn("这是warn日志...");logger.error("这是error日志...");}}

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。
scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
-->
<configuration scan="false" scanPeriod="60 seconds" debug="false"><!-- 定义日志的根目录 --><property name="LOG_HOME" value="/app/log" /><!-- 定义日志文件名称 --><property name="appName" value="atguigu-springboot"></property><!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 --><appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"><!--日志输出格式:%d表示日期时间,%thread表示线程名,%-5level:级别从左显示5个字符宽度%logger{50} 表示logger名字最长50个字符,否则按照句点分割。 %msg:日志消息,%n是换行符--><layout class="ch.qos.logback.classic.PatternLayout"><springProfile name="dev"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern></springProfile><springProfile name="!dev"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern></springProfile></layout></appender><!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->  <appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- 指定日志文件的名称 --><file>${LOG_HOME}/${appName}.log</file><!--当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动。--><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!--滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}:按天进行日志滚动 %i:当文件大小超过maxFileSize时,按照i进行文件滚动--><fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern><!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件。假设设置每天滚动,且maxHistory是365,则只保存最近365天的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除。--><MaxHistory>365</MaxHistory><!-- 当日志文件超过maxFileSize指定的大小是,根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的,必须配置timeBasedFileNamingAndTriggeringPolicy--><timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"><maxFileSize>100MB</maxFileSize></timeBasedFileNamingAndTriggeringPolicy></rollingPolicy><!-- 日志输出格式: -->     <layout class="ch.qos.logback.classic.PatternLayout"><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern></layout></appender><!-- logger主要用于存放日志对象,也可以定义日志类型、级别name:表示匹配的logger类型前缀,也就是包的前半部分level:要记录的日志级别,包括 TRACE < DEBUG < INFO < WARN < ERRORadditivity:作用在于children-logger是否使用 rootLogger配置的appender进行输出,false:表示只用当前logger的appender-ref,true:表示当前logger的appender-ref和rootLogger的appender-ref都有效--><!-- hibernate logger --><logger name="com.atguigu" level="debug" /><!-- Spring framework logger --><logger name="org.springframework" level="debug" additivity="false"></logger><!-- root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应,要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。 --><root level="info"><appender-ref ref="stdout" /><appender-ref ref="appLogAppender" /></root>
</configuration> 

log4j.properties

### set log levels ###
log4j.rootLogger = debug ,  stdout ,  D ,  E### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} ===== %5p %c{ 1 }:%L - %m%n#### 输出到日志文件 ###
#log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = logs/log.log
#log4j.appender.D.Append = true
#log4j.appender.D.Threshold = DEBUG ## 输出DEBUG级别以上的日志
#log4j.appender.D.layout = org.apache.log4j.PatternLayout
#log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
#
#### 保存异常信息到单独文件 ###
#log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = logs/error.log ## 异常日志文件名
#log4j.appender.D.Append = true
#log4j.appender.D.Threshold = ERROR ## 只输出ERROR级别以上的日志!!!
#log4j.appender.D.layout = org.apache.log4j.PatternLayout
#log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

application.properties

logging.level.atguigu=trace
#spring.profiles.active=dev#logging.path=
# 不指定路径在当前项目下生成springboot.log日志
# 可以指定完整的路径;
#logging.file=G:/springboot.log
# 在当前磁盘的根路径下创建spring文件夹和里面的log文件夹;使用?spring.log 作为默认文件
logging.path=/spring/log#  在控制台输出的日志的格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 指定文件中日志输出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
package com.atguigu.springboot;import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot03LoggingApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot03LoggingApplication.class, args);}
}

28、SpringBoot_web开发-简介

(@EnableAutoConfiguration的功效(xxAutoConfiguration给容器自动配置组件,)&)

29、SpringBoot_web开发-webjars&静态资源映射规则

(静态资源访问(所有webjars/**所有请求去/META-INF/resources/webjars/找资源,自定义资源文件默认去classpath:/META-INF/resources/ 或者去类路径下的/resources/ 或者去 /static/或者是 classpath:/public/路径下以及当前项目的根路径/寻找静态资源,不用加静态资源文件夹的名字static。欢迎页和favicon.ico的映射在静态资源下的index.html页面,)&)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>spring-boot-04-web-jsp</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>spring-boot-04-web-jsp</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><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-tomcat</artifactId><scope>provided</scope></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>
package com.atguigu.springboot;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot04WebJspApplicationTests {@Testpublic void contextLoads() {}}

hello.jsp

<%--Created by IntelliJ IDEA.User: lfyDate: 2018/3/2Time: 19:46To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h1>Hello JSP</h1><a href="abc">abc</a>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""xmlns:xsi=""xsi:schemaLocation=" .xsd"version="3.1">
</web-app>

success.jsp

<%--Created by IntelliJ IDEA.User: lfyDate: 2018/3/2Time: 19:47To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h1>SUCCESS</h1><h3>${msg}</h3>
</body>
</html>

application.properties

spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
package com.atguigu.springboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBoot04WebJspApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot04WebJspApplication.class, args);}
}
package com.atguigu.springboot;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(SpringBoot04WebJspApplication.class);}}
package com.atguigu.springboot.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class HelloController {@GetMapping("/abc")public String hello(Model model){model.addAttribute("msg","你好");return "success";}
}

30、SpringBoot_web开发-引入thymeleaf

(Thymeleaf模板引擎(html页面,引入thymeleaf springboot-starter-thymeleaf)&)

31、SpringBoot_web开发-thymeleaf语法

(Thymeleaf模板渲染(html放在templates目录下,thymeleaf就能自动渲染了,页面获取值<th:text=”${hello}”>用th任意属性值可以替换原来html属性的值,th:insert相当于jsp:include,th:each th:text=”${user}” th:each=”user:${users}” [[]]就代表t:text,th:attr做属性修改,th:attrappend,th:utext不转义,${session.user} *{firstName},@{/details(/orderId=${o.id})} /代表当前项目下)&)

32、SpringBoot_web开发-SpringMVC自动配置原理

(请解释Spring Bean的自动装配(@Bean,@Component如果有用户配置的,如果有用用户配置的,如果没有才使用默认配置的)&)

33、SpringBoot_web开发-扩展与全面接管SpringMVC

(注解@Autowired(@Configuration扩展MVC的功能 extends WebMVCConfigurerAdapter重写方法来扩展springMVC功能,既能保留自己配置也能用springBoot的自动配置 addResourcesHandlers映射webjars,@EnableWebMVC所有都为自己配置,静态页面与webjars不能访问了@ConditionalOnMissingBean(WebMVCConfigurationSupport)没有这个组件自动配置才生效,@Import(EnableWebMvcConfiguration.class)给容器中导入了一个组件自动配置失效, @Autowired(required=false)方法参数从容器中获取,将所有的相关配置一起调用容器中所有的WebMvcConfiguration一起起作用,springBoot对SpringMVC的自动配置不需要了。)&)

34、尚硅谷_SpringBoot_web开发-【实验】-引入资源

34、SpringBoot_web开发-【实验】-引入资源

(为什么选择MVCC(@RequestMapping({“/”,”/index.html”}),@Bean,th:href修改对应的html属性, @{/webjars/bootstrap/} 发送webjars请求都在类路径下找,项目访问名改变不会影响静态资源的访问)&)

35、SpringBoot_web开发-【实验】-国际化

(Locale类(国际化文件放在resources/i18n/目录下,login_zh_CN.properties,在Resource Bundle中进行配置,指定国际化资源文件基础路径,spring.messages.basename=i18n.login,页面通过th:text=”#{login.tip}”,区域信息LocaleResolver获取区域信息,默认根据请求头的locale信息来确定区域化的,th:href=”@{/index.html(l=’zh_CN’)}” 。区域信息解析器implements LocaleResolver )&)

36、SpringBoot_web开发-【实验】-登陆&拦截器

(HandlerInterceptor的处理(@PostMapping()处理post请求,@RequestParam(“username”)从请求参数获取username,如果没有提交username参数会报错,禁用模板引擎缓存spring.thymeleaf.cache=false,页面修改后crlt+F9页面重新编译。拦截器进行登录检查implements HandlerInterceptor addPathPattern(/**)可以拦截任意路径下的任意请求,excludePathPattern排除访问登录页面的请求)&)

37、SpringBoot_web开发-【实验】-Restful实验要求

(构建RESTful服务&)

restful的CRUD,

38、SpringBoot_web开发-【实验】-员工列表-公共页抽取

(Thymeleaf基础知识(th:frament=”copy”抽取公共的页面 th:insert=”~{footer::copy}” 在footer页面引入整个公共片段,th:replace声明引入的div标签替换为<footer>标签,th;include包含被引入标签里的内容,${#dates.format(emp.birth,’yyyy-MM-dd HH:mm’)})&)

查询所有员工

EmployeeController.java getMapping Model

postMapping pustMapping redirect重定向

package com.atguigu.springboot.controller;import com.atguigu.springboot.dao.DepartmentDao;
import com.atguigu.springboot.dao.EmployeeDao;
import com.atguigu.springboot.entities.Department;
import com.atguigu.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;import java.util.Collection;@Controller
public class EmployeeController {@AutowiredEmployeeDao employeeDao;@AutowiredDepartmentDao departmentDao;//查询所有员工返回列表页面@GetMapping("/emps")public String  list(Model model){Collection<Employee> employees = employeeDao.getAll();//放在请求域中model.addAttribute("emps",employees);// thymeleaf默认就会拼串// classpath:/templates/xxxx.htmlreturn "emp/list";}//来到员工添加页面@GetMapping("/emp")public String toAddPage(Model model){//来到添加页面,查出所有的部门,在页面显示Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("depts",departments);return "emp/add";}//员工添加//SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的@PostMapping("/emp")public String addEmp(Employee employee){//来到员工列表页面System.out.println("保存的员工信息:"+employee);//保存员工employeeDao.save(employee);// redirect: 表示重定向到一个地址  /代表当前项目路径// forward: 表示转发到一个地址return "redirect:/emps";}//来到修改页面,查出当前员工,在页面回显@GetMapping("/emp/{id}")public String toEditPage(@PathVariable("id") Integer id,Model model){Employee employee = employeeDao.get(id);model.addAttribute("emp",employee);//页面要显示所有的部门列表Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("depts",departments);//回到修改页面(add是一个修改添加二合一的页面);return "emp/add";}//员工修改;需要提交员工id;@PutMapping("/emp")public String updateEmployee(Employee employee){System.out.println("修改的员工数据:"+employee);employeeDao.save(employee);return "redirect:/emps";}//员工删除@DeleteMapping("/emp/{id}")public String deleteEmployee(@PathVariable("id") Integer id){employeeDao.delete(id);return "redirect:/emps";}
}

级联属性

springMvc日期Date类型转化

application.properties

#spring.resources.static-locations=classpath:/hello/,classpath:/atguigu/
# \u9879\u76EE\u8BBF\u95EE\u8DEF\u5F84
server.port=8081
server.context-path=/crud
server.tomcat.uri-encoding=UTF-8spring.mvc.date-format=yyyy-MM-dd# \u7981\u7528\u7F13\u5B58
spring.thymeleaf.cache=false # \u56FD\u9645\u5316\u914D\u7F6E\u6587\u4EF6\uFF08\u5305\u540D.\u57FA\u7840\u540D\uFF09
spring.messages.basename=i18n.login

IDEA全局搜索

39、SpringBoot_web开发-【实验】-员工列表-链接高亮&列表完成

(动态排序&)

动态排序&

40、SpringBoot_web开发-【实验】-员工添加-来到添加页面

(@GetMapping、@PostMapping、@PutMapping和@DeleteMapping注解的使用&)

@GetMapping、@PostMapping、@PutMapping和@DeleteMapping注解的使用&

41、SpringBoot_web开发-【实验】-员工添加-添加完成

(args()与“@args()”(日期格式不对,springMVC将页面提交的值转为指定的类型,默认日期格式为/,spring.mvc.date-format=yyyy-MM-dd,WebMVCAutoConfiguration)&)

42、SpringBoot_web开发-【实验】-员工修改-重用页面&修改完成

(AfterContentInit、AfterViewInit、AfterContentChecked和AfterViewChecked&)

修改判断是否为空,与新增共享一个页面

发送put请求 HiddenHttpMethodFilter

add.html

<!DOCTYPE html>
<!-- saved from url=(0052).0/examples/dashboard/ -->
<html lang="en" xmlns:th=""><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Dashboard Template for Bootstrap</title><!-- Bootstrap core CSS --><link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet"><style type="text/css">/* Chart.js */@-webkit-keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}@keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}.chartjs-render-monitor {-webkit-animation: chartjs-render-animation 0.001s;animation: chartjs-render-animation 0.001s;}</style></head><body><!--引入抽取的topbar--><!--模板名:会使用thymeleaf的前后缀配置规则进行解析--><div th:replace="commons/bar::topbar"></div><div class="container-fluid"><div class="row"><!--引入侧边栏--><div th:replace="commons/bar::#sidebar(activeUri='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><!--需要区分是员工修改还是添加;--><form th:action="@{/emp}" method="post"><!--发送put请求修改员工数据--><!--1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)2、页面创建一个post表单3、创建一个input项,name="_method";值就是我们指定的请求方式--><input type="hidden" name="_method" value="put" th:if="${emp!=null}"/><input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}"><div class="form-group"><label>LastName</label><input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}"></div><div class="form-group"><label>Email</label><input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu" th:value="${emp!=null}?${emp.email}"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><!--提交的是部门的id--><select class="form-control" name="department.id"><option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></div><button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button></form></main></div></div><!-- Bootstrap core JavaScript================================================== --><!-- Placed at the end of the document so the pages load faster --><script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script><script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script><script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script><!-- Icons --><script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script><script>feather.replace()</script></body></html>

(43、SpringBoot_web开发-【实验】-员工删除-删除完成&)

43、SpringBoot_web开发-【实验】-员工删除-删除完成&

DeleteMapping

return false取消默认行为

 

更多推荐

SpringBoot核心技术一

本文发布于:2024-02-07 09:12:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:核心技术   SpringBoot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!