spring-boot 使用自定義properties

spring-boot 使用自定義properties

配置一

使用原有的application.yml或application.properties文件mysql

application.ymlspring

custom: 
  name: lmh
  gender: 1

application.propertiessql

custom.name=lmh
custom.gender=1

定義配置類app

@ConfigurationProperties(prefix = "custom") 
public class CustomSettings {
	private String name;
	private String gender;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
}

配置二

使用新的配置文件 maple.propertiesspring-boot

maple.propertiesthis

data.username=lmh
data.password=123456
data.url=jdbc:mysql://localhost:3308/spring_boot?characterEncoding=UTF-8

定義配置類url

@Component
@ConfigurationProperties(prefix="data")
@PropertySource("classpath:config/maple.properties")
public class MapleSettings {
	private String username;
	private String password;
	private String url;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
}

使用和加載方法

@SpringBootApplication
@ServletComponentScan
@Import(value={SpringUtil.class})
@EnableConfigurationProperties({CustomSettings.class,MapleSettings.class})
public class App {
	
	public static void main(String[] args) {
		Class<?>[] c = {App.class};
		SpringApplication.run(c, args);
	}
}

調用spa

@RestController
public class DemoController {
	
    @Resource
    CustomSettings customSettings;
	
    @RequestMapping("custom")
    public Map<String, Object> custom(){
    	Map<String, Object> param = new HashMap<>();
	
        param.put("name", customSettings.getName());
        param.put("gender", customSettings.getGender());
        return param;
    }
    @RequestMapping("maple")
    public Map<String, Object> maple(){
        Map<String, Object> param = new HashMap<>();

        param.put("username", mapleSettings.getUsername());
        param.put("password", mapleSettings.getPassword());
        param.put("url", mapleSettings.getUrl());
        return param;
    }
}
相關文章
相關標籤/搜索