springboot鎬庝箞璇诲彇澶栭儴閰嶇疆鏂囦欢
Spring Boot鍙互閫氳繃浣跨敤@PropertySource娉ㄨВ鏉ヨ鍙栧閮ㄩ厤缃枃浠躲€備互涓嬫槸涓€绉嶅父瑙佺殑鏂规硶锛?/p>
- 鍒涘缓涓€涓厤缃被锛屼緥濡侫pplicationConfig锛?/li>
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
@Autowired
private Environment env;
// 瀹氫箟闇€瑕佽鍙栫殑閰嶇疆椤?/span>
@Value("${my.property}")
private String myProperty;
// 鍏朵粬閰嶇疆椤?..
// 鎻愪緵鑾峰彇閰嶇疆椤圭殑鏂规硶
public String getMyProperty() {
return myProperty;
}
// 鍏朵粬鑾峰彇閰嶇疆椤圭殑鏂规硶...
}
- 鍦╝pplication.properties鏂囦欢涓畾涔夐厤缃」锛屼緥濡傦細
my.property=value
- 鍦⊿pring Boot搴旂敤绋嬪簭鐨勫叆鍙g被涓紝閫氳繃@ComponentScan娉ㄨВ鎵弿閰嶇疆绫伙紝骞堕€氳繃@Autowired娉ㄥ叆閰嶇疆绫讳腑鐨勯厤缃」锛?/li>
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class Application {
@Autowired
private ApplicationConfig applicationConfig;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
public void init() {
// 浣跨敤閰嶇疆椤?/span>
String myProperty = applicationConfig.getMyProperty();
// 鍏朵粬浣跨敤閰嶇疆椤圭殑閫昏緫...
}
}
閫氳繃浠ヤ笂姝ラ锛屼綘灏卞彲浠ュ湪Spring Boot搴旂敤绋嬪簭涓鍙栧閮ㄩ厤缃枃浠朵腑鐨勯厤缃」浜嗐€?/p>
相关问答