SpringBoot中讀取application.properties配置文件的方法
application.properties有以下這幾條數(shù)據(jù)
方法一:@Value注解+@Component
建議properties少的時候用,多的時候就不要使用這種方法了
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Value("${wx.open.app_id}") private String appid; @Value("${wx.open.app_secret}") private String secret; @Value("${wx.open.redirect_url}") private String url; @RequestMapping("hello") public String test(){ return appid+"---"+secret+"---"+url; } }
另一種方法
創(chuàng)建一個WeProperties
@Component @Data public class WeProperties { @Value("${wx.open.app_id}") private String appid; @Value("${wx.open.app_secret}") private String secret; @Value("${wx.open.redirect_url}") private String url; }
Controller層
@RestController public class UserController { @Autowired private WeProperties properties; @RequestMapping("hello") public String test(){ return properties.getAppid()+"---"+properties.getSecret()+"---"+properties.getUrl(); } }
方法二:@Component+@ConfigurationProperties
創(chuàng)建一個WeProperties
后面的屬性名一定要保持一致
@Component @ConfigurationProperties(prefix = "wx.open") @Data public class WeProperties { private String appid; private String app_secret; private String redirect_url; }
Controller層
@RestController public class UserController { @Autowired private WeProperties properties; @RequestMapping("hello") public String test(){ return properties.getAppid()+"---"+properties.getApp_secret()+"---"+properties.getRedirect_url(); } }
方法三:@ConfigurationProperties+@EnableConfigurationProperties
創(chuàng)建一個WeProperties
后面的屬性名一定要保持一致
@ConfigurationProperties(prefix = "wx.open") @Data public class WeProperties { private String appid; private String app_secret; private String redirect_url; }
啟動類添加@EnableConfigurationProperties
@SpringBootApplication @EnableConfigurationProperties(value = WeProperties.class) public class PropertiesApplication { public static void main(String[] args) { SpringApplication.run(PropertiesApplication.class,args); } }
Controller層
@RestController public class UserController { @Autowired private WeProperties properties; @RequestMapping("hello") public String test(){ return properties.getAppid()+"---"+properties.getApp_secret()+"---"+properties.getRedirect_url(); } }
到此這篇關(guān)于SpringBoot中讀取application.properties配置文件的方法的文章就介紹到這了,更多相關(guān)SpringBoot讀取application.properties內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java分布式鎖、分布式ID和分布式事務(wù)的實現(xiàn)方案
在分布式系統(tǒng)中,分布式鎖、分布式ID和分布式事務(wù)是常用的組件,用于解決并發(fā)控制、唯一標(biāo)識和數(shù)據(jù)一致性的問題,本文將介紹Java中常用的分布式鎖、分布式ID和分布式事務(wù)的實現(xiàn)方案,并通過具體的示例代碼演示它們的用法和應(yīng)用場景2023-06-06Java LocalCache 本地緩存的實現(xiàn)實例
本篇文章主要介紹了Java LocalCache 本地緩存的實現(xiàn)實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-05-05