二、SpringBoot的配置--bilibili雷丰阳笔记

1、配置文件

application.properties

application.yml

2、yml

字面量: 数字 字符串 布尔 中间有空格 不加双引号和单引号,双引号(不会转义特殊字符)和单引号(会转义)

k: v

对象:map

friends:
	lastName: zhangsan
	age: 20

行内写法

friends: {lastName: zhangsan,age: lisi}

数组:list set

用短横线-数组元素

pets:
 - cat
 - dog
 - pig

行内写法

pets: [cat,dog,pig]

项目

从配置文件获取值

application.yml

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2017/12/12
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - zhangliu
  dog:
    name: 小狗
    age: 12

javaBean

package com.it.springboot01helloworld.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 将配置中每个文件的值,映射到这个组件中
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private boolean boss;
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

    @Override
    public 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 isBoss() {
        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.it.springboot01helloworld.bean;

public class Dog {
    private String name;
    private Integer age;

    @Override
    public 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;
    }
}

pom 导入

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

测试

package com.it.springboot01helloworld;

import com.it.springboot01helloworld.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.test.context.junit4.SpringRunner;

/**
 * 在编码的时候进行容器注入
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {

    @Autowired
    Person person;

    @Test
    public void contextLoads(){
        System.out.println(person);
    }
}

application.properties文件

person.last-name=张三
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=10

在这里插入图片描述

1.如果只需从配置文件获取一个值 @Value("${person.last-name}")

2.如果 javabean和配置文件进行映射 @ConfigurationProperties

3.@PropertySource和@ImportResource

@Component
@ConfigurationProperties(prefix = "person")
//@Validated
@PropertySource(value={"classpath:person.properties"})
public class Person {
//    @Email
    private String lastName;
    private Integer age;
    private boolean boss;
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
}

@ImportResource 导入spring配置文件

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

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01HelloworldApplication.class, args);
    }

}

/**
 * 在编码的时候进行容器注入
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {

    @Autowired
    Person person;

    @Autowired
    ApplicationContext ioc;

    @Test
    public void testHelloService(){
        boolean b = ioc.containsBean("helloService");
        System.out.println(b);
    }

    @Test
    public void contextLoads(){
        System.out.println(person);
    }
}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="com.it.springboot01helloworld.service.HelloService"></bean>
</beans>

4.Springboot推荐给容器添加组件

@Configuration
public class MyAppConfig {
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类bean给容器添加组件了。。。");
        return new HelloService();
    }

}

5.配置文件占位符

1.随机数

${random.value} 

2.占位符获取之前获得的值,如果没有可以用:获得默认值

person.last-name=李四${random.uuid}
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=${person.last-name}${person.hello:hello}dog
person.dog.age=10

6.Profile

application-dev.properties

application-prod.properties

spring.profiles.active=dev

yml

server:
  port: 8090
spring:
  profiles:
    active: dev
---
server:
  port: 8083
spring:
  profiles: dev
---

server:
  port: 8022
spring:
  profiles: prod

在启动application

Program arguments的时候添加

--spring.profiles.active=prod

VM options

-Dspring.profiles.active=prod

或者

java -jar filename.jar --spring.profiles.active=prod

7.添加项目背景

server.context-path=/boot

http://localhost:8022/boot/hello

8.还可以通过来改变默认文件的位置

–spring.config.location

项目打包以后,可以通过命令行参数的形式,启动项目来指定

java -jar filename.jar --server.port=8087 --server.context-path=/abc

配置项太多,直接将配置文件放到jar包的旁边

@EnableAutoConfiguration

解释自动配置原理 一个例子

@Configuration
@EnableConfigurationProperties({HttpEncodingProperties.class})
@ConditionalOnWebApplication
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration { 

所有配置文件的属性都在 xxxProperties中封装的

@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {

   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

根据当前的不同条件判断,决定这个配置类是否生效

springboot会加重大量自动配置类

自动配置类配置了哪些组件

会从properties中获取属性

xxxAutoConfiguration

xxxProperties

idea快捷键 查找某个类

ctrl+shift+n *AutoConfiguration

条件判断类

@ConditionalOnClass(CharacterEncodingFilter.class)

自动配置类在一定条件下才会生效

配置文件 开启debug模式

debug=true

Positive matches:
-----------------

   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:
      - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)


Negative matches:
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

   AopAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值