Spring Boot使用自定义的properties

xiaoxiao2021-02-28  47

继续在application.properties中添加

wisely2.name=wyf2 wisely2.gender=male2 定义配置类 @ConfigurationProperties(prefix = "wisely2") public class Wisely2Settings { 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; } }

若新用新的配置文件 1.5之前

建一个wisely.properties wisely.name=wangyunfei wisely.gender=male

@ConfigurationProperties(prefix = "wisely",locations = "classpath:config/wisely.properties") public class WiselySettings { 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; } } 最后注意在spring Boot入口类加上@EnableConfigurationProperties @SpringBootApplication @EnableConfigurationProperties({WiselySettings.class,Wisely2Settings.class}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

1.5版本之后 在spring boot(版本1.5.1.RELEASE)项目中,当准备映射自定义的配置文件属性到类中的时候,发现原本的@ConfigurationProperties注解已将location属性移除,因此导致无法正常给配置类的属性赋值(spring boot这么做其实也有他的道理,具体可参考https://github.com/spring-projects/spring-boot/issues/6726)

在@EnableConfigurationProperties取消激活自定义的配置类(重要) 在配置类中采用@Component的方式注册为组件,然后使用@PropertySource来指定自定义的资源目录 代码

package demo1; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * Created by LM on // */ @Component @ConfigurationProperties(prefix = "wisely") @PropertySource(value = "classpath:/wisely.properties") public class WiselySettings { @Value("${wisely.name}") private String name; @Value("${wisely.gender}") 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; } } package demo1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by LM on 2017/8/6. */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
转载请注明原文地址: https://www.6miu.com/read-79553.html

最新回复(0)