依据Spring Boot学习视频写的笔记
一、入门
resources时类路径的根路径
1.使用Spring Initializer快速创建Spring Boot项目
默认生成的有主程序,只需要编写自己的应用逻辑就行
主程序已经生成好,只需要编写自己的业务逻辑即可
resourse文件夹结构:
static:静态文件夹
templates:模板文件夹(保存所有的模板页面),内嵌tomcat,使用jar包,默认不支持Jsp
application.properties:Spring Boot应用的配置文件,可以修改一些默认的配置文件,比如端口号,数据库,连接池等
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent>
依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
spring-boot-starter-web:
spring-boot-starter: spring-boot的场景启动器;导入了web模块正常运行所依赖的组件;
spring-boot将所有的场景都抽取出来,做成一个个的starter启动器,我们只需要引入对应场景的启动器就行
2.主程序类
@SpringBootApplicationpublic class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
@SpringBootApplication是主配置类,main方法来启动spring boot应用
@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:spring boot的配置类
@Configuration:配置类,配置类也是容器里的组件
@EnableAutoConfiguration:开启自动配置功能
@AutoConfigurationPackage@Import({AutoConfigurationImportSelector.class})
@Import:Spring的底层注解,给容器中导入组件
类AutoConfigurationPackages.register.class将主配置类所在包及下面所有子包里面的所有组件扫描到Spring容器;
给容器中导入非常多的自动配置类
SpringBoot在启动的时候,从META-INF/spring.factories里面的自动配置类来导入组件
所有场景需要的组件全部通过自动配置类来添加进容器
二、配置文件
1、基础
spring boot使用一个全局的配置文件
yml 以数字为中心
server:port: 8080
properties
server.port=8082
配置文件:修改springBoot自动配置的默认值;SpringBoot都在底层给我们自动配置好了
2、语法
字面量:普通的值(数值,字符串,布尔)
k:v 字面直接写
字符串的书写规范:
双引号:不会转义
name:"nihao \n list": 输出:nihao 换行 list
单引号:转义
name:'nihao \n list': 输出:nihao \n list
对象、Map(属性和值)(键值对) 在下一行来写对象的属性和值的关系,注意缩进
friends:name:Jackieage:18
行内
friends:{name:jackie,age:18}
数组或者列表
pets:- dog- cat- bird
行内
pets:[dog,cat,bird]
3、配置文件注入
有个依赖需要配置
配置文件处理器,配置文件绑定就会有提示
spring-boot-configuration-processor
类上的注解:比如Person类上注解为@Component和@ConfigurationProperties(profix="person")
配置文件上yml格式:
person:name:jackieage:19
从单元测试中来测试
@Autowired
private Person person;
yml语法中
lastName和last-name是一样的,系统认为last-name中-后的字母也是大写
因为idea的编码为utf-8编码,而properties文件不是utf-8编码,所以需要在settings中设置 file encoding改为utf-8,且将那个勾打上,否则直接使用properties文件中的值时,会出现乱码问题。
application.properties的配置文件
person.age=12person.birth=2017/12/12person.boss=falseperson.last-name=jackieperson.lists=a,b,cperson.maps.k1=qperson.maps.k2=wperson.maps.k3=e
Person类:
@Component//@ConfigurationProperties(prefix = "person")public class Person {@Value("${person.last-name}")private String lastName;@Value("#{2*12}")private Integer age;@Value("true")private Boolean boss;**********}
单元测试类进行测试
@RunWith(SpringRunner.class)@SpringBootTestpublic class DemoesApplicationTests {@Autowiredprivate Person person;@Testpublic void contextLoads() {System.out.println(person.getLastName()+"--"+person.getAge()+"--"+person.getBoss());}}
结果
4、@Value和@ConfigurationProperties比较
@ConfigurationProperties @Value 功能 批量注入配置文件中的属性 一个个指定 松散绑定(松散语法) 支持 不支持 SpEL 不支持 支持 JSR303数据校验 支持 不支持 复杂类型封装 支持 不支持
只是在某个业务逻辑中需要获取一个配置文件中的某项值,使用@Value
如果专门编写一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties
5、其他配置文件
新建一个person.properties的配置文件
person.age=12person.boss=falseperson.last-name=李四person.maps.k1=v1person.maps.k2=v2person.lists=a,b,cperson.dog.name=wanghuahuperson.dog.age=15
在JavaBean的Person类中添加注解 @PropertySource(value={"classpath:person.properties"}),@Component,@ConfigurationProperties(prefix="person")
注意()里面可以有{}也可以直接用“”,但是{}里面必须要有“”
结果:
ApplicationContext是一个非常重要的类,针对Spring容器有一些重要的方法
获取配置值
person.age=${random.int}
person.boss=false
person.last-name=张三${random.uuid}
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=${person.last-name}'s wanghuahu
person.dog.age=15
6、配置文件的加载位置
SpringBoot启动扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
file:./config/ 右击当前项目进行创建配置文件
file./
classpath:/config/ 在resources文件夹下创建配置文件
classpath:/
优先级从高到低顺序,高优先级会覆盖低优先级的相同配置;互补配置 即会加载全部的配置文件,然后有互补的效果
7、引入外部配置
SpringBoot也可以从以下位置加载配置;优先级从高到低;高优先级覆盖低优先级,可以互补
命令行参数
java -jar spring-boot-config-02-0.0.1-SNAPSHOT.jar --server.port=9005 --server.context-path=/abc
中间一个空格
来自java:comp/env的JNDI属性
java系统属性(System.getProperties())
操作系统环境变量
RandomValuePropertySource配置的random.*属性值
优先加载profile, 由jar包外到jar包内
jar包外部的application-{profile}.properties或application.yml(带Spring.profile)配置文件
jar包内部的application-{profile}.properties或application.yml(带Spring.profile)配置文件
jar包外部的application.properties或application.yml(带Spring.profile)配置文件**
jar包内部的application.properties或application.yml(不带spring.profile)配置文件
@Configuration注解类的@PropertySource
通过SpringApplication.setDefaultProperties指定的默认属性
官方文档
8、自动配置原理
1)、SpringBoot启动的时候加载主配置类,开启自动配置功能,@EnableAutoConfiguration
2)、@EnableAutoConfiguration 作用:
利用AutoConfigurationImportSelector给容器中导入一些组件?
可以查看selectImports()方法的内容
获取候选的配置
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
扫描类路径下的
SpringFactoriesLoader.loadFactoryNames()扫描所有jar包类路径下的 MATA-INF/spring.factories把扫描到的这些文件的内容包装成properties对象从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加到容器中
将类路径下 MATE-INF/spring.factories里面配置的所有的EnableAutoConfiguration的值加入到了容器中;
3)、每一个自动配置类进行自动配置功能;
4)、以HttpEncodingAutoConfiguration 为例
@Configuration //表示是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties({HttpEncodingProperties.class})//启动指定类的Configurationproperties功能;将配置文件中的值和HttpEncodingProperties绑定起来了;并把HttpEncodingProperties加入ioc容器中
@ConditionalOnWebApplication//根据不同的条件,进行判断,如果满足条件,整个配置类里面的配置就会失效,判断是否为web应用;
(type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})//判断当前项目有没有这个类,解决乱码的过滤器
@ConditionalOnProperty(prefix = "spring.http.encoding",value = {"enabled"},matchIfMissing = true
)//判断配置文件是否存在某个配置 spring.http.encoding,matchIfMissing = true如果不存在也是成立,即使不配置也生效
public class HttpEncodingAutoConfiguration {//给容器添加组件,这个组件的值需要从properties属性中获取private final HttpEncodingProperties properties;//只有一个有参数构造器情况下,参数的值就会从容器中拿public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {this.properties = properties;}@Bean@ConditionalOnMissingBeanpublic CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpEncodingProperties.Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpEncodingProperties.Type.RESPONSE));return filter;}
5)、所有在配置文件中能配置的属性都是在xxxProperties类中封装着;配置文件能配置什么就可以参照某个功能对应的这个属性类
@ConfigurationProperties(prefix = "spring.http.encoding")//从配置文件中的值进行绑定和bean属性进行绑定
public class HttpEncodingProperties {
根据当前不同条件判断,决定这个配置类是否生效?
一旦这个配置类生效;这个配置类会给容器添加各种组件;这些组件的属性是从对应的properties中获取的,这些类里面的每个属性又是和配置文件绑定的
9、所有的自动配置组件
每一个xxxAutoConfiguration这样的类都是容器中的一个组件,都加入到容器中;
作用:用他们做自动配置
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
整个Spring Boot的精髓:
1)、SpringBoot启动会加载大量的自动配置类
2)、我们只需要看我们所需要的功能有没有框架本身所写好的默认配置类
3)、查看这个配置类中添加了哪些组件
4)、添加组件时,会从properties类中获取属性,这个属性就是我们可以在配置文件中指定或者使用框架默认的
给容器中添加组件
xxxProperties:封装配置文件中的属性;
用@Bean添加进容器
细节注意点:
@Conditional派生注解
@Conditional:必须要在指定条件成立时,才给容器中添加组件,即配置里面的所有内容才生效;
@Conditional派生注解 | 作用(判断是否满足当前指定条件) |
---|---|
@ConditionalOnJava | 系统的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在指定Bean |
@ConditionalOnMissBean | 容器中不存在指定Bean |
@ConditionalOnExpression | 满足spEL表达式 |
@ConditionalOnClass | 系统中有指定的类 |
@ConditionalOnMissClass | 系统中没有指定的类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
@ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否存在指定的资源文件 |
@ConditionalOnWebApplication | 当前是web环境 |
@ConditionalOnNotWebApplication | 当前不是web环境 |
@ConditionalOnJndi | JNDI存在指定项 |
自动配置报告
自动配置类必须在一些条件下才会生效
可以在application.properties中添加:
debug=true
自动配置报告
============================CONDITIONS EVALUATION REPORT
============================Positive matches:(启动的,匹配成功的)
-----------------CodecsAutoConfiguration matched:- @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)......Negative matches:(没有启动的,没有匹配成功的)
-----------------ActiveMQAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
.....
三、日志
市面上的日志框架
日志抽象层 | 日志实现 |
---|---|
JCL(Jakarta Commons Logging) SLF4j(Simple Logging Facade for Java) jboss-logging | Log4j JUL(java.util.logging) Log4j2 Logback |
左边的抽象,右边的实现
SLF4J -- Logback
Spring Boot:底层是Spring框架,Spring默认框架是JCL;
SpringBoot选用SLF4J和logback
slf4j:
每个日志框架的实现框架都有自己的配置文件。使用slf4j以后,配置文件还是做成日志实现框架本身的配置文件;
a系统(slf4j+logback):Spring(commons-logging)、Hibernate(jboss-logging)、Mybatis
统一日志框架,即使是别的框架和我一起统一使用slf4j进行输出;
核心:
1、将系统中其他日志框架排除出去;
2、用中间包来替换原有的日志框架/
3、导入slf4j的其他实现
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId><version>2.1.9.RELEASE</version><scope>compile</scope>
</dependency>
SpringBoot的日志功能
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId><version>2.0.1.RELEASE</version><scope>compile</scope>
</dependency>
总结:
SpringBoot底层也是使用SLF4J+log4jback
SpringBoot也把其他日志替换成了slf4j
起着commons.loggings的名字其实new的SLF4J替换中间包
SpringBoot2中改成了bridge
如果要引入其他框架?一定要把这个框架的日志依赖移除掉,而且底层
Spring Boot能自动适配所有的日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉
日志的使用
1、默认配置
trace-debug-info-warn-error
可以调整需要的日志级别进行输出,不用注释语句。
//记录器
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads() {//日志的级别//从低到高//可以调整输出的日志级别;日志就只会在这个级别以后的高级别生效logger.trace("这是trace日志");logger.debug("这是debug信息");//SpringBoot默认给的是info级别,如果没指定就是默认的root级别logger.info("这是info日志");logger.warn("这是warn信息");logger.error("这是Error信息");
}
调整指定包的日志级别在配置文件中进行配置
logging.level.com.wdjr=trace
控制台输出的日志格式
#%d:日期
#%thread:线程号
#%-5level:靠左 级别
#%logger{50}:全类名50字符限制,否则按照句号分割
#%msg:消息+换行
#%n:换行
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
SpringBoot修改日志的默认配置
logging.level.com.wdjr=trace
#不指定path就是当前目录下生成springboot.log
#logging.file=springboot.log
#当前磁盘下根路径创建spring文件中log文件夹,使用spring.log作为默认
logging.path=/spring/log
#控制台输出的日志格式 日期 + 线程号 + 靠左 级别 +全类名50字符限制+消息+换行
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
#指定文件中日志输出的格式
logging.pattern.file=xxx
2、指定配置
2、指定配置
给类路径下放上每个日志框架自己的配置文件即可;SpringBoot就不会使用自己默认的配置
logging System | Customization |
---|---|
Logback | logback-spring.xml ,logback-spring.groovy,logback.xml or logback.groovy |
Log4J2 | log4j2-spring.xml or log4j2.xml |
JDK(Java Util Logging) | logging.properties |
logback.xml直接被日志框架识别 ,logback-spring.xml日志框架就不直接加载日志配置项,由SpringBoot加载
<springProfile name="dev"><!-- 可以指定某段配置只在某个环境下生效 -->
</springProfile>
<springProfile name!="dev"><!-- 可以指定某段配置只在某个环境下生效 -->
</springProfile>
如何调试开发环境,输入命令行参数
--spring.profiles.active=dev
如果不带后面的xx-spring.xml就会报错
切换日志框架
可以根据slf4j的日志适配图,进行相关切换;
1、log4j
slf4j+log4j的方式;
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><artifactId>logback-classic</artifactId><groupId>ch.qos.logback</groupId></exclusion></exclusions>
</dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId>
</dependency>
不推荐使用仅作为演示
2、log4j2
切换为log4j2
<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>
四、web开发
1、简介
使用SpringBoot;
1)、创建SpringBoot应用,选中我们需要的模块;
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码
自动配置原理?
这个场景的SpringBoot帮我们配置了什么?能不能修改?能修改那些配置?能不能扩展?xxx
xxxAutoConfiguration:帮我们给容器中自动配置组件
xxxProperties:配置类来封装配置文件的内容
public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");} else {Duration cachePeriod = this.resourceProperties.getCache().getPeriod();CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();if (!registry.hasMappingForPattern("/webjars/**")) {this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}}
}
2、静态资源文件映射规则
1、webjar
1)、所有的/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;
webjars:以jar包的方式引入静态资源
http://www.webjars.org/
localhost:8080/webjars/jquery/3.3.1/jquery.js
2、本地资源
private String staticPathPattern = "/**";
访问任何资源
2、会在这几文件夹下去找静态路径(静态资源文件夹)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
"/";当前项目的根路径
localhost:8080/abc ==>去静态资源文件夹中找abc
3、index页面欢迎页,静态资源文件夹下所有的index.html页面;被“/**”映射;
localhost:8080/ -->index页面
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),this.mvcProperties.getStaticPathPattern());
}
4、喜欢的图标,即网站title的图标favicon
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {private final ResourceProperties resourceProperties;public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;}@Beanpublic SimpleUrlHandlerMapping faviconHandlerMapping() {SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);//把任何favicon的图标都在静态文件夹下找mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",faviconRequestHandler()));return mapping;}@Beanpublic ResourceHttpRequestHandler faviconRequestHandler() {ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();requestHandler.setLocations(this.resourceProperties.getFaviconLocations());return requestHandler;}}
可以在配置文件配置静态资源文件夹
spring.resources.static-locations=classpath:xxxx
3、模板引擎
将html和数据 结合到一起 输出组装处理好的新文件
4、SpringMVC自动配置
1、SpringMVC的自动导入
Spring框架
自动配置好了mvc:
以下是SpringBoot对SpringMVC的默认
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.自动配置了ViewResolver(视图解析器:根据方法的返回值决定视图对象(View),视图对象然后再决定如何渲染(转发还是重定向))
ContentNegotiatingViewResolver`组合所有视图解析器
如何定制:我们可以自己给容器中添加一个视图解析器;自动将其整合进来
Support for serving static resources, including support for WebJars (see below).静态资源
Static
index.html
support.Custom
Favicon
support (see below).
自动注册 了
Converter
,GenericConverter
,Formatter
beans.Converter
:类型转换 文本转为字面量Formatter
:格式化器 转换后格式转换
@Bean @ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件配置入职格式化的规则 public Formatter<Date> dateFormatter() {return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件 }
自己添加的格式化转换器,只需要放在容器中即可
Support for
HttpMessageConverters
(see below)HttpMessageConverters:转换HTTP转换和响应:User - json
HttpMessageConverters:是从容器中确定;获取所有的HttpMessageConverters,将自己的组件注册在容器中 @Bean
If you need to add or customize converters you can use Spring Boot’s
HttpMessageConverters
class:
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;@Configuration
public class MyConfiguration {@Beanpublic HttpMessageConverters customConverters() {HttpMessageConverter<?> additional = ...HttpMessageConverter<?> another = ...return new HttpMessageConverters(additional, another);}}
Automatic registration of
MessageCodesResolver
(see below).定义错误代码生成规则
Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).
@Override
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {try {return this.beanFactory.getBean(ConfigurableWebBindingInitializer.class);}catch (NoSuchBeanDefinitionException ex) {return super.getConfigurableWebBindingInitializer();}
}
在beanFactory:中可以自己创建一个,初始化webDataBinder
请求数据 ==》javaBean
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration
class of type WebMvcConfigurerAdapter
, but without @EnableWebMvc
. If you wish to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
or ExceptionHandlerExceptionResolver
you can declare a WebMvcRegistrationsAdapter
instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
.
思想:修改默认配置
2、扩展SpringMVC
编写一个配置类,类型是WebMvcConfigurerAdapter(继承),使用WebMvcConfigurerAdapter可以扩展,不能标注@EnableWebMvc;既保留了配置,也能拓展我们自己的应用
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);//浏览器发送wdjr请求,也来到success页面registry.addViewController("/wdjr").setViewName("success");}
}
原理:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();//从容器中获取所有webMVCconfigurer@Autowired(required = false)public void setConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);@Overrideprotected void addViewControllers(ViewControllerRegistry registry) {this.configurers.addViewControllers(registry);}//一个参考实现,将所有的webMVCconfigurer相关配置一起调用(包括自己的配置类)@Override// public void addViewControllers(ViewControllerRegistry registry) {// for (WebMvcConfigurer delegate : this.delegates) {//delegate.addViewControllers(registry);//}}}}
3)、自己的配置被调用
效果:SpringMVC的自动配置和我们的扩展配置都会起作用
3、全面接管mvc
不需要SpringBoot对SpringMVC的自动配置。
例如静态资源访问,不推荐全面接管
原理:
为什么@EnableWebMvc注解,SpringBoot对SpringMVC的控制就失效了
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {@Override
public void addViewControllers(ViewControllerRegistry registry) {// super.addViewControllers(registry);//浏览器发送wdjr请求,也来到success页面registry.addViewController("/wdjr").setViewName("success");}
}
1)、核心配置
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
2)、DelegatingWebMvcConfiguration
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3)、WebMvcAutoConfiguration
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,WebMvcConfigurerAdapter.class })
//容器没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
4)、@EnableWebMvc将WebMvcConfigurationSupport导入进来了;
5)、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能
5、修改SpringMVC默认配置
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2)、在SpringBoot中会有 xxxConfigurer帮助我们扩展配置。
6、登录拦截器
1、登录
开发技巧
1、清除模板缓存
2、Ctrl+F9刷新
1、新建一个LoginController
@Controller
public class LoginController {@PostMapping(value ="/user/login")public String login(@RequestParam("username")String username,@RequestParam("password")String password,Map<String,Object> map){if(!StringUtils.isEmpty(username) && "123456".equals(password)){//登录成功return "list";}else{map.put("msg", "用户名密码错误");return "login";}}
}
2、登录错误消息显示
<!--判断-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
3、表单重复提交
表单重复提交事件 --》重定向来到成功页面--》模板引擎解析
if(!StringUtils.isEmpty(username) && "123456".equals(password)){//登录成功,防止重复提交return "redirect:/main.html";
}else{map.put("msg", "用户名密码错误");return "login";
}
模板引擎解析
@Override
public void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("/main.html").setViewName("Dashboard");
}
7、拦截器
作用:实现权限控制,每个页面请求前中后,都会进入到拦截器进行处理(登录权限)
1、在component下新建一个LoginHandlerInterceptor拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {//目标方法执行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object user = request.getSession().getAttribute("loginUser");if(user!=null){//已经登录return true;}//未经过验证request.setAttribute("msg", "没权限请先登录");request.getRequestDispatcher("/index.html").forward(request, response);return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}
//转发到主页面
request.getRequestDispatcher("/index.html").forward(request, response);
2、在MyMvcConfig配置中重写拦截器方法,加入到容器中
//所有的webMvcConfigurerAdapter组件会一起起作用
@Bean //註冊到容器去
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("/main.html").setViewName("Dashboard");}//注册拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {//静态资源 css js img 已经做好了静态资源映射registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");}};return adapter;
}
3、在LoginHandler中添加登录成功写入session
@Controller
public class LoginController {@PostMapping(value ="/user/login")public String login(@RequestParam("username")String username,@RequestParam("password")String password,Map<String,Object> map,HttpSession session){if(!StringUtils.isEmpty(username) && "123456".equals(password)){//登录成功,防止重复提交session.setAttribute("loginUser", username);return "redirect:/main.html";}else{map.put("msg", "用户名密码错误");return "login";}}
}
日期格式化
属性中添加 date-formate 默认是 /
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")
public Formatter<Date> dateFormatter() {return new DateFormatter(this.mvcProperties.getDateFormat());
}@Override
public MessageCodesResolver getMessageCodesResolver() {if (this.mvcProperties.getMessageCodesResolverFormat() != null) {DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver();resolver.setMessageCodeFormatter(this.mvcProperties.getMessageCodesResolverFormat());return resolver;}return null;
}
spring.mvc.date-format=yyyy-MM-dd
8、错误机制的处理
1、默认的错误处理机制
原理参照
ErrorMvcAutoConfiguration:错误处理的自动配置
org\springframework\boot\spring-boot-autoconfigure\1.5.12.RELEASE\spring-boot-autoconfigure-1.5.12.RELEASE.jar!\org\springframework\boot\autoconfigure\web\ErrorMvcAutoConfiguration.class
DefaultErrorAttributes
帮我们在页面共享信息
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,boolean includeStackTrace) {Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();errorAttributes.put("timestamp", new Date());addStatus(errorAttributes, requestAttributes);addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);addPath(errorAttributes, requestAttributes);return errorAttributes;
}
BasicErrorController
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {//产生HTML数据@RequestMapping(produces = "text/html")public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {HttpStatus status = getStatus(request);Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));response.setStatus(status.value());ModelAndView modelAndView = resolveErrorView(request, response, status, model);return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);}//产生Json数据@RequestMapping@ResponseBodypublic ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {Map<String, Object> body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));HttpStatus status = getStatus(request);return new ResponseEntity<Map<String, Object>>(body, status);}
ErrorPageCustomizer
@Value("${error.path:/error}")
private String path = "/error";//系统出现错误以后来到error请求进行处理,(web.xml)
DefaultErrorViewResolver
@Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,Map<String, Object> model) {ModelAndView modelAndView = resolve(String.valueOf(status), model);if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);}return modelAndView; }private ModelAndView resolve(String viewName, Map<String, Object> model) {//默认SpringBoot可以找到一个页面?error/状态码String errorViewName = "error/" + viewName;//如果模板引擎可以解析地址,就返回模板引擎解析TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);if (provider != null) {//有模板引擎就返回到errorViewName指定的视图地址return new ModelAndView(errorViewName, model);}//自己的文件 就在静态文件夹下找静态文件 /静态资源文件夹/404.htmlreturn resolveResource(errorViewName, model); }
一旦系统出现4xx或者5xx错误 ErrorPageCustomizer就回来定制错误的响应规则,就会来到 /error请求,BasicErrorController处理,就是一个Controller
1.响应页面,去哪个页面是由 DefaultErrorViewResolver 拿到所有的错误视图
protected ModelAndView resolveErrorView(HttpServletRequest request,HttpServletResponse response, HttpStatus status, Map<String, Object> model) {for (ErrorViewResolver resolver : this.errorViewResolvers) {ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);if (modelAndView != null) {return modelAndView;}}return null;
}
l浏览器发送请求 accpt:text/html
客户端请求:accept:/*
2、如何定制错误响应
1)、如何定制错误的页面
1.有模板引擎:静态资源/404.html,什么错误什么页面;所有以4开头的 4xx.html 5开头的5xx.html
有精确的404和4xx优先选择404
页面获得的数据
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常信息
errors:JSR303有关
2.没有放在模板引擎,放在静态文件夹,也可以显示,就是没法使用模板取值
3.没有放模板引擎,没放静态,会显示默认的错误
如何定制Json数据
1、仅发送json数据
public class UserNotExitsException extends RuntimeException {public UserNotExitsException(){super("用户不存在");}
}
/*** 异常处理器*/
@ControllerAdvice
public class MyExceptionHandler {@ResponseBody@ExceptionHandler(UserNotExitsException.class)public Map<String ,Object> handlerException(Exception e){Map<String ,Object> map =new HashMap<>();map.put("code", "user not exist");map.put("message", e.getMessage());return map;}
}
无法自适应 都是返回的json数据
2、转发到error自适应处理
@ExceptionHandler(UserNotExitsException.class)
public String handlerException(Exception e, HttpServletRequest request){Map<String ,Object> map =new HashMap<>();//传入自己的状态码request.setAttribute("javax.servlet.error.status_code", 432);map.put("code", "user not exist");map.put("message", e.getMessage());//转发到errorreturn "forward:/error";
}
程序默认获取状态码
protected HttpStatus getStatus(HttpServletRequest request) {Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");if (statusCode == null) {return HttpStatus.INTERNAL_SERVER_ERROR;}try {return HttpStatus.valueOf(statusCode);}catch (Exception ex) {return HttpStatus.INTERNAL_SERVER_ERROR;}
没有自己写的自定义异常数据
3、自适应和定制数据传入
Spring 默认的原理,出现错误后回来到error请求,会被BasicErrorController处理,响应出去的数据是由BasicErrorController的父类AbstractErrorController(ErrorController)规定的方法getAttributes得到的;
1、编写一个ErrorController的实现类【或者AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json数据返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
容器中的DefaultErrorAtrributes.getErrorAtrributees();默认进行数据处理
public class MyErrorAttributes extends DefaultErrorAttributes {@Overridepublic Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);map.put("company", "wdjr");return map;}
}
异常处理:把map方法请求域中
@ExceptionHandler(UserNotExitsException.class)public String handlerException(Exception e, HttpServletRequest request){Map<String ,Object> map =new HashMap<>();//传入自己的状态码request.setAttribute("javax.servlet.error.status_code", 432);map.put("code", "user not exist");map.put("message", e.getMessage());request.setAttribute("ext", map);//转发到errorreturn "forward:/error";}
}
在上面的MyErrorAttributes类中加上
//我们的异常处理器
Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
map.put("ext", ext);
9、注册Servlet三大组件
三大组件 Servlet Filter Listener
由于SprringBoot默认是以jar包启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml
注册三大组件
MyServlet
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("Hello Servlet");}
}
ServletRegistrationBean
@Bean
public ServletRegistrationBean myServlet(){ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/servlet");return servletRegistrationBean;
}
FilterRegistrationBean
MyFilter
public class MyFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("MyFilter process");chain.doFilter(request, response);}@Overridepublic void destroy() {}
}
FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(new MyFilter());filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return filterRegistrationBean;
}
MyListener
public class MyListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println(".........web应用启动..........");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println(".........web应用销毁..........");}
}
ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());return registrationBean;
}
SpringBoot帮助我们自动配置SpringMVC的时候,自动注册SpringMVC的前端控制器;DispatcherServlet;
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)public ServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet) {ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet, this.serverProperties.getServletMapping());//默认拦截 /所有请求 包括静态资源 不包括jsp//可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);registration.setLoadOnStartup(this.webMvcProperties.getServlet().getLoadOnStartup());if (this.multipartConfig != null) {registration.setMultipartConfig(this.multipartConfig);}return registration;}}
五、Docker
1、简介
Docker是一个开源的应用容器引擎
将软件编译成一个镜像;然后在镜像里各种软件做好配置,将镜像发布出去,其他的机器如果想使用这个软件就可以直接使用这个镜像。运行中的这个镜像叫做容器,容器启动速度快,类似ghost操作系统,安装好了什么都有了;
2、Docker的核心概念
docker主机(HOST):安装了Docker程序的机器(Docker直接安装在操作系统上的)
docker客户端(Client):操作docker主机
docker仓库(Registry):用来保存打包好的软件镜像
docker镜像(Image):软件打好包的镜像,放到docker的仓库中
docker容器(Container):镜像启动后的实例(5个容器启动5次镜像)
docker的步骤:
1、安装Docker
2、去Docker仓库找到这个软件对应的镜像;
3、使用Docker运行的这个镜像,镜像就会生成一个容器
4、对容器的启动停止,就是对软件的启动和停止
3、安装Docker
在linux上安装docker
1、查看centos版本
# uname -r
3.10.0-693.el7.x86_64
要求:大于3.10
如果小于的话升级*(选做)
# yum update
2、安装docker
# yum install docker
3、启动docker
# systemctl start docker
# docker -v
4、开机启动docker
# systemctl enable docker
5、停止docker
# systemctl stop docker
docker的常用操作
1、镜像操作
1、搜索
docker search mysql
2、拉取
默认最新版本
# docekr pull mysql
安装指定版本
# docker pull mysql:5.5
3、查看
docker images
4、删除
docker rmi imageid
2、容器操作
软件的镜像(qq.exe) -- 运行镜像 -- 产生一个容器(正在运行的软件)
1、搜索镜像
# docker search tomcat
2、拉取镜像
# docker pull tomcat
3、根据镜像启动容器
[root@lion ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/tomcat latest d3d38d61e402 35 hours ago 549 MB
[root@lion ~]# docker run --name mytomcat -d tomcat:latest
2f0348702f5f2a2777082198795d8059d83e5ee38f430d2d44199939cc63e249
4、查看那个进程正在进行
[root@lion ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2f0348702f5f tomcat:latest "catalina.sh run" 41 seconds ago Up 39 seconds 8080/tcp mytomcat
5、停止运行中容器
[root@lion ~]# docker stop 2f0348702f5f
2f0348702f5f
6、查看所有容器
[root@lion ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2f0348702f5f tomcat:latest "catalina.sh run" 52 minutes ago Exited (143) 2 minutes ago mytomcat
7、启动容器
[root@lion ~]# docker start 2f0348702f5f
8、删除docker容器
[root@lion ~]# docker rm 2f0348702f5f
2f0348702f5f
9、端口映射
[root@lion ~]# docker run --name mytomcat -d -p 8888:8080 tomcat
692c408c220128014df32ecb6324fb388427d1ecd0ec56325580135c58f63b29
虚拟机:8888
容器的:8080
-d:后台运行
-p:主机端口映射到容器端口
浏览器:192.168.179.129:8888
10、docker的日志
[root@lion ~]# docker logs 692c408c2201
11、多个启动
[root@lion ~]# docker run -d -p 9000:8080 --name mytomcat2 tomcat
浏览器:192.168.179.129:9000
3、安装Mysql
docker pull mysql
docker run --name mysql001 -e MYSQL_ROOT_PASSWORD -d -p 3307:3306 mysql
六、数据访问
1、整合JDBC数据源
1、新建项目 spring-boot-06-data-jdbc
WEB
Mysql
JDBC
SpringBoot1.5
2、编写配置文件appliction.yml
pring:datasource:username: rootpassword: Welcome_1url: jdbc:mysql://192.168.179.131:3306/jdbcdriver-class-name: com.mysql.jdbc.Driver
3、编写测试类测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot06DataJdbcApplicationTests {@AutowiredDataSource dataSource;@Testpublic void contextLoads() throws SQLException {System.out.println(dataSource.getClass());Connection connection = dataSource.getConnection();System.out.println(connection);connection.close();}}
4、测试结果
class org.apache.tomcat.jdbc.pool.DataSource
ProxyConnection[PooledConnection[com.mysql.jdbc.JDBC4Connection@c35af2a]]
数据源相关配置都在DataSourceProperties属性里
1、DataSource
参考DataSourceConfiguration,根据配置创建数据源,默认是使用tomcat连接池,可以使用spring.datasource.type指定自定义的数据源
2、SpringBoot默认支持
Tomcat数据源
HikariDataSource
dbcp.BasicDataSource
dbcp2.BasicDataSource
3、自定义数据源
*/
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {@Beanpublic DataSource dataSource(DataSourceProperties properties) {//使用builder创建数据源,利用反射创建相应的type数据源,并绑定数据源return properties.initializeDataSourceBuilder().build();}}
1、导入Druid的依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version>
</dependency>
2、修改配置文件
spring:datasource:username: rootpassword: Welcome_1url: jdbc:mysql://192.168.179.131:3306/jdbcdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource
# schema:
# - classpath:department.sql
server:port: 9000
已经替换了原来的tomcat数据源
3、配置Druid数据源配置
spring:datasource:username: rootpassword: Welcome_1url: jdbc:mysql://192.168.179.131:3306/jdbcdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource# 初始化大小,最小,最大 initialSize: 5minIdle: 5maxActive: 20# 配置获取连接等待超时的时间 maxWait: 60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉监控界面sql无法统计,‘wall’用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20userGlobalDataSourceStat: true# 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:department.sql
server:port: 9000
4、Druid配置监控
@Configuration
public class DruidConfig {//一定要有这个来将阿里的数据源添加进容器@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid的监控//1、配置一个管理后台@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");Map<String,String> initParams =new HashMap<>();initParams.put("loginUsername", "admin");initParams.put("loginPassword", "123456");bean.setInitParameters(initParams);return bean;}//2、配置监控的filter@Beanpublic FilterRegistrationBean webstatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParams =new HashMap<>();initParams.put("exclusions", "*.js,*.css,/druid/*");bean.setInitParameters(initParams);bean.setUrlPatterns(Arrays.asList("/*"));return bean;}}
5、运行测试,访问 localhost:9000/druid
2、整合Mybatis
1、新建工程,SpringBoot1.5+web+JDBC+Mysql
导入依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2、导入配置文件中关于Druid的配置
2.1、导入依赖
2.2、配置文件application.yml(指定用户名密码...配置Druid的配置参数,修改sql文件加载的默认名)
2.3、将Druid组件加入到容器中(监控)重点
具体同上
3、创建数据表department和employee表
3.1、根据sql文件,新建两张表
3.2、修改加载的sql名(默认为schema.sql和schema-all.sql)
spring:datasource:schema:- classpath:sql/department.sql- classpath:sql/employeee.sql
3.3、运行程序检查数据库是否创建成功
4、创建数据库对应的JavaBean (驼峰命名,getter/setter toString/注释掉schema防止重复创建)
在配置文件中修改驼峰命名开启 ,不写配置文件就写配置类
mybatis:configuration:map-underscore-to-camel-case: true
//类名冲突所以全类名
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);}};}
}
注解方式
5、新建mapper
//指定是一个mapper
@Mapper
public interface DepartmentMapper {@Insert("insert into department(dept_name) value(#{deptName})")public int insertDept(Department department);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Update("update department set dept_Name=#{deptName} where id=#{id}")public int updateDept(Department department);@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);}
6、编写controller测试
@RestController
public class DeptController {@AutowiredDepartmentMapper departmentMapper;@RequestMapping("/getDept/{id}")public Department getDepartment(@PathVariable("id") Integer id){return departmentMapper.getDeptById(id);}@RequestMapping("/delDept/{id}")public int delDept(@PathVariable("id") Integer id){return departmentMapper.deleteDeptById(id);}@RequestMapping("/update/{id}")public int updateDept(@PathVariable("id") Integer id){return departmentMapper.updateDept(new Department(id, "开发部"));}@GetMapping("/insert")public int insertDept(Department department){return departmentMapper.insertDept(department);}
}
问题:
mapper文件夹下有多个mapper文件,加麻烦,可以直接扫描整个mapper文
件夹下的mapper
//主配置类或者mybatis配置类
@MapperScan(value = "com.wdjr.springboot.mapper")
配置文件方式
1、新建文件
2、新建mybatis的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>
3、新建Employee的接口方法
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insetEmp(Employee employee);
}
4、新建Employee的mapper.xml的映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wdjr.springboot.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.wdjr.springboot.bean.Employee">select * from employee where id=#{id}</select><insert id="insetEmp">INSERT INTO employee(last_name,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})</insert>
</mapper>
5、修改application.yml配置文件
mybatis:config-location: classpath:mybatis/mybatis-config.xmlmapper-locations: classpath:mybatis/mapper/*.xml
6、新建一个Controller访问方法
@RestController
public class EmployeeController {@AutowiredEmployeeMapper employeeMapper;@RequestMapping("/getEmp/{id}")public Employee getEmp(@PathVariable("id") Integer id){return employeeMapper.getEmpById(id);}@GetMapping("/insertEmp")public Employee insertEmp(Employee employee){employeeMapper.insetEmp(employee);return employee;}
}
JPA数据访问
新建工程 springBoot1.5+Web+JPA+MYSQL+JDBC
目录结构
1、新建一个实体类User
//使用JPA注解配置映射关系
@Entity//告诉JPA这是一个实体类(和数据表映射的类)
@Table(name="tbl_user") //@Table来指定和那个数据表对应,如果省略默认表明就是user;public class User {@Id //这是一个主键@GeneratedValue(strategy = GenerationType.IDENTITY)//自增组件private Integer id ;@Column(name="last_name",length = 50) //这是和数据表对应的一个列private String lastName;@Column//省略默认列名就是属性名private String email;@Columnpublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}
2、新建一个UserRepository来继承jpa的绝大多数功能
//继承jpaRepository
public interface UserRepository extends JpaRepository<User,Integer> {}
3、编写配置文件application.yml
spring:datasource:url: jdbc:mysql://192.168.179.131/jpausername: rootpassword: Welcome_1driver-class-name: com.mysql.jdbc.Driverjpa:hibernate:#更新或创建ddl-auto: updateshow-sql: true
4、编写Controller测试
@RestController
public class UserController {@AutowiredUserRepository userRepository;@GetMapping("/user/{id}")public User getUser(@PathVariable("id") Integer id){User user = userRepository.findOne(id);return user;}@GetMapping("/insert")public User insertUser(User user){User user1 = userRepository.save(user);return user1;}
}
七、SpringBoot的自定义starter
starter:场景启动器
1、场景需要使用什么依赖?
2、如何编写自动配置
@Configuration //指定这个类是一个配置类
@ConditionalOnXXX //在指定条件下成立的情况下自动配置类生效
@AutoConfigureAfter //指定自动配置类的顺序
@Bean //给容器中添加组件@ConfigurationProperties //结合相关xxxProperties类来绑定相关的配置
@EnableConfigurationProperties //让xxxProperties生效加到容器中自动配置类要能加载
将需要启动就加载的自动配置类,配置在META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
3、模式
启动器空的jar只需要做依赖管理导入;
专门写一个自动配置模块;
启动器依赖自动配置,别人只需要引入starter
xxx-spring-boot-starter
重点部分
HelloProperties
package com.lxy.starter;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties(prefix = "lxy.hello")
public class HelloProperties {private String prefix;private String suffix;public String getPrefix() {return prefix;}public void setPrefix(String prefix) {this.prefix = prefix;}public String getSuffix() {return suffix;}public void setSuffix(String suffix) {this.suffix = suffix;}
}
HelloService
package com.lxy.starter;public class HelloService {HelloProperties helloProperties;public HelloProperties getHelloProperties() {return helloProperties;}public void setHelloProperties(HelloProperties helloProperties) {this.helloProperties = helloProperties;}public String sayHello(String name){return helloProperties.getPrefix()+name+helloProperties.getSuffix();}
}
HelloServiceAutoConfiguration
package com.lxy.starter;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {@AutowiredHelloProperties helloProperties;@Beanpublic HelloService helloService(){HelloService service = new HelloService();service.setHelloProperties(helloProperties);return service;}}
配置文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.lxy.starter.HelloServiceAutoConfiguration
修改lxy-spring-boot-starter 也就是之前的Maven项目,修改pom文件引入autoconfiguration依赖
<dependencies><dependency><groupId>com.lxy.starter</groupId><artifactId>lxy-spring-boot-starter-autoconfigurer</artifactId><version>0.0.1-SNAPSHOT</version></dependency> </dependencies>
install生成
测试
新建一个springboot 1.5+web
1、引入starter
<dependency><groupId>com.lxy.starter</groupId><artifactId>lxy-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>
2、新建一个Controller用来测试
@RestController
public class HelloController {@AutowiredHelloService helloService;@GetMappingpublic String hello(){return helloService.sayHello("test");}
}
3、编写配置文件制定前缀和后缀名
lxy.hello.prefix=Starter-
lxy.hello.suffix=-Success
运行访问http://localhost:8080/hello
驼峰:
不用全部都标@mapper:
依据Spring Boot学习视频写的笔记相关推荐
- Spring Boot学习笔记(1)
文章目录 Spring Boot学习笔记(1) Spring Boot 整合 JSP Spring Boot HTML Thymeleaf 常用语法 Spring Boot 数据校验 Spring B ...
- Spring Boot学习笔记-进阶(3)
文章目录 Spring Boot学习笔记-进阶(3) 一.Spring Boot与缓存 二.Spring Boot与消息 三.Spring Boot与检索 四.Spring Boot与任务 异步任务 ...
- Spring Boot学习笔记-基础(2)
Spring Boot学习笔记-基础(2) Spring Boot 优点: – 快速创建独立运行的Spring项目以及与主流框架集成 – 使用嵌入式的Servlet容器,应用无需打成WAR包 – st ...
- Spring Boot学习笔记-实践建言
2019独角兽企业重金招聘Python工程师标准>>> 本文延续<Spring Boot学习笔记-快速示例>,从开发指南中摘出一些实践经验可供参考.这也是笔者看到的眼前一 ...
- Vue + Spring Boot 学习笔记02:引入数据库实现用户登录功能
Vue + Spring Boot 学习笔记02:引入数据库实现用户登录功能 在学习笔记01里,我们利用跨域打通了前端的Vue与后端的Spring Boot,实现了用户登录功能,但是后台的登录控制器在 ...
- Vue + Spring Boot 学习笔记01:实现用户登录功能
Vue + Spring Boot 学习笔记01:实现用户登录功能 一.创建后端Spring Boot项目Book Management 二.创建前端Vue项目bm-vue 三.修改后端项目Book ...
- 超赞:不愧是阿里内部“Spring boot学习笔记”从头到尾,全是精华
spring boot为何会出现? 随着动态语言的流行(Ruby.Groovy. Scala. Node.js),Java 的开发显得格外的笨重:繁多的配置.低下的开发效率.复杂的部署流程以及第三方技 ...
- Spring Boot学习笔记-Nginx+Jar包部署项目
写在前面 之前用Spring Boot写的获取英雄联盟战绩的小项目,只是上传到了Github上,Github地址:lol-api.一直没时间部署到服务器上.今天,找时间部署好了,网址是:api.51c ...
- 15 个优秀开源的 Spring Boot 学习项目,一网打尽!
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
最新文章
- 【IBM Tivoli Identity Manager 学习文档】3 系统部署
- Spring Cloud Hystrix理解与实践(一):搭建简单监控集群
- 什么是初效过滤器_初效过滤器主要用于过滤多少微米的杂质?
- 安卓应用安全指南 5.3.2 将内部账户添加到账户管理器 规则书
- TextView赋值int型,并显示
- 多元线性回归dw值_SPSS教程10:多元线性回归
- OpenStack 安装教程(使用Fuel )
- 虚拟化发展历程及原理
- 【Linux】ROS机器人操作系统的安装与使用
- linux usb转串口驱动报错,USB转串口驱动编译出错
- spring mvc 的ajax传参详解
- 儿童讲堂 - 量词的解释
- html修改progress背景色,html5progress标签如何更改进度条颜色?progress进度条详解
- python做用友财务报表_用友财务软件怎样生成财务报表?
- 探探php模板下载,PHP开发的优客365网址导航商业精华版1.1.6版本源码带WAP手机版附带三款模板和四款插件_随便下源码网...
- Sorry, name can only contain URL-friendly characters and name can no longer contain capital letters
- Git修改以前某次历史提交注释
- 动态绑定和静态绑定详解
- ORACLE数据库介绍
- asm路径出现DB_UNKNOWN