开发中,经常会有一些常量,变动较少,但是我们不能在java代码中写死,这样每次修改都得去java代码中修改,引用地方较多时我们需要修改很多java文件;所以我们可以集中写在某个配置文件中,这样只用修改配置文件就好
lv:
name: hlvy
password: 123456
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* @author : kaifa
* create at: 2019-10-18 14:36
* @description: springboot读取配置文件信息
*/
//lombok
@Data
@Component
public class User implements Serializable {
@Value("${lv.name}")
private String name;
@Value("${lv.password}")
private String password;
}
package com.boot.boot_banner_yml.controller;
import com.boot.boot_banner_yml.profile.Account;
import com.boot.boot_banner_yml.profile.Text;
import com.boot.boot_banner_yml.profile.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author : kaifa
* create at: 2019-10-18 14:47
* @description: 测试读取配置文件
*/
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
private User user;
/**
* @Value 读取application.yml数据
* @return
*/
@RequestMapping("user")
public User readFileUser(){
return user;
}
}
package com.boot.boot_banner_yml.profile;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* @author : kaifa
* create at: 2019-10-18 14:36
* @description: springboot读取配置文件信息
*/
//配置文件前缀
@ConfigurationProperties(prefix="lv")
@Component
//lombok
@Data
public class Account implements Serializable {
/**
* 这里不需要写@value注解了 这里的名字与配置文件一致
*/
private String name;
private String password;
}
@Autowired
private Account account;
/**
* 读取application.yml数据
* 读取前缀
* @return
*/
@RequestMapping("account")
public Account readFileAccount(){
return account;
}
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* @author : kaifa
* create at: 2019-10-18 14:36
* @description: springboot读取配置文件信息
*/
//配置文件前缀
@ConfigurationProperties(prefix="val")
// 获取外部的配置文件文件,需要指定配置文件的路径
@PropertySource(
value = "classpath:val.properties",
encoding = "utf-8"
)
@Component
//lombok
@Data
public class Text implements Serializable {
/**
* 这里不需要写@value注解了 这里的名字与配置文件一致
*/
private String text;
}
@Autowired
private Text text;
/**
* 自定义val.yml读取文件
* @return
*/
@RequestMapping("text")
public Text readFileText(){
return text;
}