springboot中使用自定义的properties属性
在application.properties中添加属性
ai.name=明
ai.age=22
ai.sex=男
定义配置类如下,前缀(prefix)可自定义修改,本文为 ai。
@ConfigurationProperties(prefix = “ai”)
public class PropertiesSetting1 {
private String name;
private Long age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
若使用新的配置文件,需新建一个ai.properties。
ai.name=婷婷
ai.age=22
ai.sex=女
配置如下配置类,需要指定ai.properties的位置。
@ConfigurationProperties(prefix = “ai”,locations=”classpath:config/ai.properties”)
public class Properties1Setting {
private String name;
private Long age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
在Controller中调用,
@Autowired
private PropertiesSetting propertiesSetting;
@Autowired
private Properties1Setting properties1Setting;
@RequestMapping("/properties")
public @ResponseBody String properties(){
System.out.println("姓名:"+propertiesSetting.getName()+",年龄:"+propertiesSetting.getAge()
+",性别:"+propertiesSetting.getSex());
System.out.println("姓名:"+properties1Setting.getName()+",年龄:"+properties1Setting.getAge()
+",性别:"+properties1Setting.getSex());
return "ok";
}
在项目的启动类上面添加@EnableConfigurationProperties注解,如下。
@SpringBootApplication
@EnableConfigurationProperties({PropertiesSetting.class,Properties1Setting.class})
public class SpringbootNewApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootNewApplication.class, args);
}
运行项目,控制台输出结果,到此配置完成。
(idea为例)如果控制台输出的中文是乱码,需要在
File—>Settings—>File Encodings进行设置如下图。
重新运行,乱码问题解决。