介绍
可以看到官方提供的压缩包中的 src/main/resources 目录下有一个 application.properties 配置文件
(如果没有就手动创建一个),这就是 Spring Boot 默认的配置文件
,可以对其进行更改来修改 Spring Boot 的配置。其格式形式如下:
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password= 000000
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sell?characterEncoding=utf-8&useSSL=false
在这里我对本地数据库进行了配置
@Value的使用
properties 中除了填写 Spring Boot 的配置信息外也可以自定义属性
,比如在其中添加:
sell.name = 林俊杰
思考:对于自定义配置属性,我们如何在 Spring Boot 中使用它们呢?
我们新建一个controller
层TestController
文件。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
// 使用 @Value 注解注入属性值
@Value("${sell.name}")
private String name;
@GetMapping("/hello")
public String test() {
return String.format("Hello %s!", name);
}
}
当我们在终端输入以下指令:
curl 'http://localhost:8080/v1/hello'
我们能看到如下显示:
Hello 林俊杰!
注意: 这里
只能访问 application.properties 中的属性
,对于其他自定义的配置文件中的属性是无法访问
的,我们还需要进行其他处理。
自定义配置文件路径
假设我们我们配置文件路径如下:
/Users/Home/Desktop/hotsell/src/main/resources/config/test.properties
配置文件内容如下:
sell.name = 周杰伦
思考:我们要如何才能读取到该路径下的配置文件呢?
在这里我们使用@PropertySource
,它是spring的注解,用来加载指定的属性文件的配置
到 Spring 的环境中。
@RestController
//@PropertySource注解告知spring加载 classpath 目录下的 config/test.properties 文件。
@PropertySource(value = "classpath:config/test.properties")
public class TestController {
@Value("${sell.name}")
private String name;
@GetMapping("/hello")
public String test() {
return String.format("Hello %s!", name);
}
}
当我们在终端输入以下指令:
curl 'http://localhost:8080/v1/hello'
我们能看到如下显示:
Hello 周杰伦!
使用类的方式来进行文件配置
现在我们新建一个配置类NameConfiguration
,具体代码如下:
package com.hotsell.core.configuration;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "sell")
@PropertySource(value = "classpath:config/test.properties")
public class NameConfiguration {
private String name;
}
然后我们在controller
层中的TestController
进行代码测试:
import com.hotsell.core.configuration.NameConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private NameConfiguration name;
@GetMapping("/hello")
public String test() {
String nickName = name.getName();
return String.format("Hello %s!", nickName);
}
}
当我们在终端输入以下指令:
curl 'http://localhost:8080/v1/hello'
我们能看到如下显示:
Hello 周杰伦!
可见我们配置成功了,这就是目前比较主流的配置方式。
网友评论