SpringBoot快速创建和配置

一、快速创建SpringBoot项目

在这里插入图片描述

package com.sun.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;

// @ResponseBody 表示这个类的所有方法返回的数据,直接写给浏览器(对象则转为json数据)
//RestController是@ResponseBody和@Controller的合体

@RestController
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello()
    {
        return "hello world quick";
    }
}

其中注意事项:

1.@ResponseBody 表示这个类的所有方法返回的数据,直接写给浏览器(对象则转为json数据)

2.RestController是@ResponseBody和@Controller的合体

3.resources文件夹中的目录情况:
static:保存所有的静态资源;js css images;WebContent
templates:保存所有的模板页面;(springboot默认jar包使用嵌入式Tomcat,默认不支持jsp页面);可以使用模板引擎(freemark,thymeleaf);
application.properties:SpringBoot应用配置文件,可以修改一些默认设置如端口:
server.port=8081

其他:cache为缓存

二、SpringBoot配置

1、配置文件

作用:修改springboot自动配置默认值
两种形式:
•application.properties
•application.yml

Yml和XML对比:
YAML以数据为中心适合做配置文件

2、YML配置

1、基本语法:

①k:空格v:表示一对键值对;
②空格控制层级关系
③属性和值大小写敏感

2、值的写法

字面量:普通的值(数字、字符串、布尔)
k: v直接写,双引号不转义
对象(属性和值)(键值对):
k: v:在下一行写对象的属性和值关系,注意缩进

friends:
    lastName: san
    age:20
行内写法:
friends: {lastName: san,age:20}

数组(List,Set):
用 - 表示元素

pets:
- cat
- dog
- pig
行内写法:
pets:[cat,dog,pig]

3、值映射

将yam配置文件中每个属性的值映射到这个组件中
遇到的问题:@ConfigurationProperties报错
解决方法:
①增加依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

②增加@Component及前缀

@Component
@ConfigurationProperties(prefix="person")

注意:
1.测试的时候要用public修饰符才可以运行
2.在properties中配置属性导致中文乱码,在settings中设置将ASC编码修改为utf-8

person.last-name=张三
person.age=30
person.birth=2030/01/03
person.boss=false
person.dog.name=dog
person.dog.age=42
person.lists=a,b,c
person.maps.k1=v1
person.maps.k2=32

在这里插入图片描述

3、value配置(和ConfigurationProperties区别)

@ConfigurationProperties@Value
功能批量注入配置文件中的属性一个一个指定
松散绑定语法×
SpEL×
JSR303数据校验x
复杂类型封装x
使用情况专门编写javaBean来和配置文件映射时在某个业务逻辑中需要获取配置文件中的某项值使用

松散绑定语法:值Person.lastName可写成Person.last_name等
复杂类型封装值
SpEL表达式:配置文件中获取值/#{SpEL}

    @Value("#{11*2}")
    private Integer age;

JSR303数据校验:指注入值的时候校验

//需要在类上加@Validated
    @Email
    private String lastName;
        <!--JSR303数据校验需要的包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

4、@PropertySource&@ImportSource区别

区别@PropertySource@ImportSource
作用起到指定配置文件路径的作用导入spring配置文件,让配置文件内容生效

@ConfigurationProperties(prefix="") 默认从全局配置文件中加载值,起到加载哪个对象的作用。

@ConfigurationProperties(prefix="person")

@PropertySource(“classpath:person.properties”)起到指定路径的作用

@PropertySource("classpath:person.properties")

上面两者要配合使用。

@ImportSource
SpringBoot里面Spring配置文件,我们自己编写的配置文件也不能自动识别,所以需要ImportSource

@ImportResource(locations = {"classpath:bean.xml"})
@SpringBootApplication
public class Springboot02ConfigApplication {

SpringBoot推荐给容器中添加组件的方式 (全注解):
1、创建配置类(类似spring配置文件)
2、使用@bean给容器中添加组件

@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中,这个容器中组件默认的id就是方法名
    @Bean
    public HelloService helloService()
    {
        System.out.println("配置类@bean给容器中添加组件");
        return new HelloService();
    }
}

5、配置文件占位符

1、在yml或properties中写随机数

person.last-name=张三${random.uuid}
person.age=${random.int}

2、获取配置中的值

person.last-name=张三${random.uuid}
person.dog.name=${person.last-name}_dog

6、Profile

概念:是Sprig对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境

1.多Profile文件

在编写主配置文件时加入,如application-{profile}.properties/yml

默认使用application.properties配置

2.yml支持多文档块方式

在这里插入图片描述

server:
  port: 8080
spring:
  profiles:
    active: dev
---
server:
  port: 8083
spring:
  profiles: dev
---
server:
  port: 8084
  spring:
    profiles: abc

3.激活指定Profile

1、在application.properties配置文件中指定激活的

spring.profiles.active=dev

在这里插入图片描述

2、命令行切换
如:
spring.profiles.active=dev

在这里插入图片描述

在这里插入图片描述
3、虚拟机传参
在这里插入图片描述

7、SpringBoot配置文件加载位置

springboot会自动扫描以下位置的application.properties或者application.yml文件作为SpringBoot的配置
优先级(由高到低,高优先级会覆盖低优先级)为:

  • 项目下 config文件
  • 项目下根目录
  • 类路径下config文件
  • 类根目录
    在这里插入图片描述
    其他:
#配置项目访问路径
server.servlet.context-path=/boot02

可以通过spring.config.location来改变默认的配置文件位置;
项目打包后用命令行参数形式,指定配置文件新位置

在这里插入图片描述

8、外部配置加载顺序

SpringBoot可以从以下位置加载配置;按优先级从高到低

  • 命令行参数
    直接用命令行修改默认配置,多个配置用空格
    eg:
    在这里插入图片描述
    优先加载带profile的(由jar包外向内寻找)

  • jar包外application-{profile}.properties或application.yml,带(spring.profile)配置文件

  • jar包内application-{profile}.properties或application.yml,带(spring.profile)配置文件

再加载不带profile

  • jar包外application-{profile}.properties或application.yml,不带(spring.profile)配置文件
  • jar包内application-{profile}.properties或application.yml,不带(spring.profile)配置文件
    在这里插入图片描述
    jar包外的配置会自动执行

9、自动配置原理

官方文档:

https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#common-application-properties

自动配置原理

  1. SpringBoot启动时加载主配置类,开启自动配置功能@EnableAutoConfiguration
  2. @EnableAutoConfiguration作用:
  • 利用AutoConfigurationImportSelector.class给容器中导入组件
  • 查看AutoConfigurationEntry()方法的内容
 List<String> configurations =getCandidateConfigurations(annotationMetadata, attributes);

SpringFactoriesLoader.loadFactoryNames
扫描所有jar包类路径下的META-INF/spring.factories
把扫描到的这些文件内容包装成properties对象
从properties中获取EnableAutoConfiguration类的值,把他们添加到容器中

类路径下的META-INF/spring.factories里面配置的EnableAutoConfiguration加入到容器中,用他们做自动配置

# 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.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
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.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
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.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
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.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
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.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
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.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
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.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
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.ClientHttpConnectorAutoConfiguration,\
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,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
  1. 每一个自动配置类进行自动配置功能
  2. HttpEncodingAutoConfiguration为例解释自动配置原理
    该类上的注解
@Configuration(proxyBeanMethods = false)//配置类
@EnableConfigurationProperties(ServerProperties.class)//启动指定器类的ConfigurationProperties功能,将配置文件对应的值和HttpEncodingAutoConfiguration绑定
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)//spring底层@Conditional注解,根据不同条件,如果满足指定的条件,整个配置类才会生效。判断当前应用是否为web应用
@ConditionalOnClass(CharacterEncodingFilter.class)//判断当前项目有没有CharacterEncodingFilter这个类,SpringMVC中进行乱码的过滤器
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)//判断配置文件中是否存在某个配置server.servlet.encoding.enabled如果不存在也成立
//即使我们配置文件中不配置	server.servlet.encoding.enabled也是默认生效的。

public class HttpEncodingAutoConfiguration {

	@Bean //给容器中添加一个组件,这个组件的某些值会从properties中获取
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
		return filter;
	}
}

根据当前不同的条件判断,决定这个配置类是否生效;
一旦这个配置类生效,这个配置类就会给容器添加各种组件;这个组件的属性是从对应的properties类中获取的,这些类里的每个属性又是和配置文件绑定的。

精髓:
1)springboot启动会加载大量的自动配置类
2)看所需功能有没有SpringBoot默认写好的自动配置类
3)这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配了)
4)给容器中自动配置类添加组件的时候,会从properties中获取某些属性。我们就可以在配置文件中指定这些属性的值。

xxxAutoConfiguration:自动配置类
给容器中添加组件
xxxProperties:封装配置文件中相关 *

  1. 所有在配置文件中能配置的属性都是在xxxProperties封装着
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {

10、自动配置报告

1、@Conditional派生注解
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置类里的内容才生效
在这里插入图片描述
自动配置类在一定的条件下生效

我们怎么知道哪些配置类生效:
我们可以通过启用debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值