一、配置文檔配置項(xiàng)的調(diào)用
啟動(dòng)后在瀏覽器直接輸入http://localhost:18080/user/test,就直接打印出配置文件中的配置內(nèi)容。
二、綁定對(duì)象bean調(diào)用
有時(shí)候?qū)傩蕴嗔耍粋€(gè)個(gè)綁定到屬性字段上太累,官方提倡綁定一個(gè)對(duì)象的bean,這里我們建一個(gè)ConfigBean.java類,頂部需要使用注解@ConfigurationProperties(prefix = “com”)來(lái)指明使用哪個(gè)
@ConfigurationProperties(prefix = "com")public class ConfigBean { private String name; private String id; // 省略getter和setter}
這里配置完還需要在spring Boot入口類加上@EnableConfigurationProperties并指明要加載哪個(gè)bean,如果不寫ConfigBean.class,在bean類那邊添加
@SpringBootApplication@EnableConfigurationProperties({ConfigBean.class})public class Chapter2Application { public static void main(String[] args) { SpringApplication.run(Chapter2Application.class, args); }}
最后在Controller中引入ConfigBean使用即可,如下:
@RestControllerpublic class UserController { @Autowired ConfigBean configBean; @RequestMapping("/") public String hexo(){ return configBean.getName()+configBean.getId(); }}
三、參數(shù)間引用
在application.properties中的各個(gè)參數(shù)之間也可以直接引用來(lái)使用,就像下面的設(shè)置:
com.name="張三"com.id="8"com.psrInfo=${com.name}編號(hào)為${com.id}
這樣我們就可以只是用psrInfo這個(gè)屬性就好
四、使用自定義新建的配置文件
我們新建一個(gè)bean類,如下:
@Configuration@ConfigurationProperties(prefix = "com.md") @PropertySource("classpath:test.properties")public class ConfigTestBean { private String name; private String want; // 省略getter和setter}
主要就是加了一個(gè)注解:@PropertySource("classpath:test.properties")
五、配置文件優(yōu)先級(jí)
application.properties和application.yml文件可以放在一下四個(gè)位置:
同樣,這個(gè)列表按照優(yōu)先級(jí)排序,也就是說(shuō),src/main/resources/config下application.properties覆蓋src/main/resources下application.properties中相同的屬性,如圖:
此外,如果你在相同優(yōu)先級(jí)位置同時(shí)有application.properties和application.yml,那么application.yml里面的屬性就會(huì)覆蓋application.properties里的屬性。
ps:下面看下SpringBoot讀取application.properties文件
SpringBoot讀取application.properties文件,通常有3種方式
1. @Value 例如:
@Value("${spring.profiles.active}")private String profileActive;------相當(dāng)于把properties文件中的spring.profiles.active注入到變量profileActive中
2. @ConfigurationProperties 例如:
@Component@ConfigurationProperties(locations = "classpath:application.properties",prefix="test")public class TestProperties {String url;String key;}
其他類中使用時(shí),就可以直接注入該TestProperties 進(jìn)行訪問(wèn)相關(guān)的值
3. 使用Enviroment 例如:
private Enviroment env;env.getProperty("test.url");
而env方式效率較低
注:@ConfigurationProperties也可用于其他.properties文件,只要locations指定即可
總結(jié)
以上所述是小編給大家介紹的Spring Boot中配置文件application.properties使用,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選