2-springboot核心配置与注解

全局配置文件

是什么?

application.properties

application.yml

放在哪里?

 src/main/resource目录或者类路径的/config

什么作用?

存储配置信息,供整个项目使用

例如:

Spring Boot提供的属性及它们的默认值

application.properties配置文件使用演示

1.使用springbootstarter创建项目,选择web依赖

2.创建com.itheima.domain包,Pet和Person类

public class Pet {

    private String type;
    private String name;

    //getter 、setter、toString补上

}
@Component// 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中
public class Person {

    private int id;            //id
    private String name;      //名称
    private List hobby;       //爱好
    private String[] family; //家庭成员
    private Map map;
    private Pet pet;          //宠物

    //getter 、setter、toString补上
}

3.在配置文件中自动提示属性

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

更新工程:在项目上右键 maven-->update project...

target/classes/META-INF 下会生成文件 spring-configuration-metadata.json。

4. application.properties中自定义属性

##对实体类对象Person进行属性配置
person.id=1
person.name=tom
person.hobby=play,read,sleep
person.family=father,mother
person.map.k1=v1
person.map.k2=v2
person.pet.type=dog
person.pet.name=kity

5.查看配置效果

@SpringBootTest
class Chapter02ApplicationTests {

    @Autowired
    private Person person;

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

    }
}

application.yaml 配置文件

概念:

YAML文件格式是Spring Boot支持的一种JSON超集文件格式。

相较于传统的Properties配置文件,YAML文件以数据为核心,是一种更为直观且容易被电脑识别的数据序列化格式。

application.yaml文件的工作原理和application.properties一样。

语法 key:(空格)value,使用缩进控制层级关系

1.  value的值为普通数据类型

server:
    port:  8081
    path:  /hello

2.value的值为数组和单列集合

person:
  hobby:  [play,read,sleep]

3.  value的值为Map集合或对象

person:
    map: {k1: v1,k2: v2}

测试

1.创建application.yaml

person:
  id: 2
  name: 张三
  hobby: [sing,read,sleep]
  family: [father,mother]
  map: {k1: v1,k2: v2}
  pet: {type: cat, name: tom}

2.删除application.properties,因为会覆盖yaml中属性

配置文件属性值的注入

使用@ConfigurationProperties注入属性

@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private int id;      

    public void setId(int id) {

        this.id = id;
    
    }
}

注意使用@ConfigurationProperties注解批量注入属性值时,要保证配置文件中的属性与对应实体类的属性一致,否则无法正确获取并注入属性值。

使用@Value注入属性

使用@Value注解对每一个属性注入设置,免去了属性setXX()方法

1.准备实体类

@Component  // 用于将Student类作为Bean注入到Spring容器中
public class Student {

    @Value("${person.id}")
    private int id;      //id

    @Value("${person.name}")
    private String name; //名称

    private List hobby;  //爱好
    private String[] family; //家庭成员
    private Map map;
    private Pet pet;   //宠物

    //重写 toString() 
}

2.测试

@Autowired
private Student student;
@Test
void testStudent() {
    System.out.println(student);
}

两种注解的对比分析

对比点

@ConfigurationProperties

@Value

底层框架

Spring Boot

Spring

功能

批量注入配置文件中的属性

单个注入

属性setXX()方法

需要

不需要

复杂类型属性注入

支持

不支持

松散绑定

支持

不支持

JSR303数据校验

支持

不支持

SpEL表达式

不支持

支持

JSR303数据校验

JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。


Bean Validation 1.0 (JSR 303)

举例:邮箱校验

1.添加依赖

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

2.修改Person类

@Component// 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中
@Validated
public class Person {

    private int id;            //id

    @Email  //import org.hibernate.validator.constraints.Email;
    private String name;      //名称

添加上面两个注解后,再做测试,会报错

default message [不是一个合法的电子邮件地址];

Spring Boot自定义配置

使用@PropertySource加载properties配置文件

作用

1.在resources目录下,新建配置文件test.properties

#对实体类对象MyProperties进行属性注入

test.id=110
test.name=test

2.在domain包下,新建MyProperties类

@Component
@PropertySource("classpath:test.properties")// 指定自定义配置文件位置和名称
@ConfigurationProperties(prefix = "test")      // 指定配置文件注入属性前缀
public class MyProperties {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //重写toString()
}

3.在测试类里添加

@Autowired
private MyProperties myProperties;

@Test
void testMyProperties() {
    System.out.println(myProperties);
}

使用@ImportResource加载XML配置文件

1.建包com.itheima.config和建类MyService

public class MyService {

}

2.在resources目录下建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="myService" class="com.itheima.config.MyService" />
</beans>

3.启动类上添加@ImportResource("classpath:beans.xml")

4.在测试类里添加

@Autowired
private ApplicationContext applicationContext;

@Test
void testIoc() {

    System.out.println(applicationContext.containsBean("myService"));

}

使用@Configuration编写自定义配置类

1.新建一个类MyConfig

@Configuration   // 定义该类是一个配置类
public class MyConfig {

    @Bean        // 将返回值对象作为组件添加到Spring容器中,该组件name默认为方法名
    public MyService myService(){
        return new MyService();
    }
}

2.注释掉@ImportResource做测试

Profile多环境配置

目的让系统自动适应不同的运行环境

Profile文件多环境配置

1.编写多个环境配置

格式:application-{profile}.properties

application-dev.properties  server.port=8081

application-test.properties  server.port=8082

application-prod.properties server.port=8083

2.激活指定环境

控制台 java -jar xxx.jar --spring.profiles.active=dev

或者

修改全局配置文件application.properties   spring.profiles.active=dev 重启项目

@Profile注解多环境配置

@Profile:作用于类,通过value属性指定环境配置

以模拟不同数据库配置为例

1.建包config,建接口DBConnector

public interface DBConnector {

    public void configure();

}

2.建三个实现类模拟三种数据库配置

@Configuration
@Profile("dev")    // 指定多环境配置类标识
public class DevDBConnector implements DBConnector {

    @Override
    public void configure() {

        System.out.println("数据库配置环境dev");

    }

}
@Configuration
@Profile("prod")   // 指定多环境配置类标识
public class ProdDBConnector implements DBConnector {

    @Override
    public void configure() {

        System.out.println("数据库配置环境prod");

    }

}
@Configuration
@Profile("test")   // 指定多环境配置类标识
public class TestDBConnector implements DBConnector {

    @Override
    public void configure() {

        System.out.println("数据库配置环境test");

    }

}

3.激活某个数据库配置环境

修改全局配置文件application.properties   spring.profiles.active=dev

4.测试是否激活

建包controller 及控制类

@RestController
public class DBController {

    @Autowired
    private DBConnector dbConnector;

    @GetMapping("/showDB")
    public void showDB(){

        dbConnector.configure();

    }

}

启动项目,在浏览器里输入http://localhost:8081/showDB

随机值设置 (RandomValuePropertySource提供)

${random.xx}   xx表示随机数类型和范围

示例

my.secret=${random.value} //配置随机字符串

my.number=${random.int} //配置随机整数

my.bignumber=${random.long} //配置随机长整数

my.uuid=${random.uuid}         //配置随机UUID

my.number.less.than.ten=${random.int(10)}   //配置小于10的随机整数

my.number.in.range=${random.int[1024,65536]}//配置在[1024,65536]的随机整数

参数间引用

${xx}  xx表示先前在配置文件中已经配置过的属性名。

示例

app.name=MyApp

app.description=${app.name} is a Spring Boot application

测试随机值及参数间引用

1.在全局配置文件添加两个测试属性

tom:
    age: ${random.int[10,20]}
    description: tom的年龄可能是${tom.age}

2.测试类里添加

    @Value("${tom.description}")
    private String description;

    @Test
    public void placeholderTest() {

        System.out.println(description);

    }

作业:

        application.yaml中的配置信息注入到Person对象中去

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值