springboot鎬庝箞璇诲彇閰嶇疆鏂囦欢
鍦⊿pring Boot涓紝鍙互閫氳繃@Value
娉ㄨВ銆?code>Environment鎺ュ彛銆?code>@ConfigurationProperties娉ㄨВ绛夋柟寮忔潵璇诲彇閰嶇疆鏂囦欢銆?/p>
- 浣跨敤
@Value
娉ㄨВ璇诲彇閰嶇疆鏂囦欢涓殑鍊硷細
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${my.property}")
private String myProperty;
// ...
public void doSomething() {
System.out.println(myProperty);
}
}
涓婅堪浠g爜涓紝@Value("${my.property}")
娉ㄨВ鐢ㄤ簬灏嗛厤缃枃浠朵腑my.property
鐨勫€兼敞鍏ュ埌myProperty
灞炴€т腑銆?/p>
- 浣跨敤
Environment
鎺ュ彛璇诲彇閰嶇疆鏂囦欢涓殑鍊硷細
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Autowired
private Environment env;
// ...
public void doSomething() {
String myProperty = env.getProperty("my.property");
System.out.println(myProperty);
}
}
涓婅堪浠g爜涓紝閫氳繃env.getProperty("my.property")
鏂规硶鏉ヨ幏鍙栭厤缃枃浠朵腑my.property
鐨勫€笺€?/p>
- 浣跨敤
@ConfigurationProperties
娉ㄨВ璇诲彇閰嶇疆鏂囦欢涓殑鍊硷細
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String property;
// ...
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
涓婅堪浠g爜涓紝@ConfigurationProperties(prefix = "my")
娉ㄨВ鐢ㄤ簬灏嗕互my
涓哄墠缂€鐨勯厤缃枃浠跺睘鎬у€兼敞鍏ュ埌鍚屽悕鐨勫睘鎬т腑銆傚湪application.properties
閰嶇疆鏂囦欢涓紝鍙互閫氳繃my.property
鏉ヨ缃?code>property灞炴€х殑鍊笺€?/p>
娉ㄦ剰锛氬湪浣跨敤@ConfigurationProperties
娉ㄨВ鏃讹紝闇€瑕佸湪涓荤被涓婃坊鍔?code>@EnableConfigurationProperties(MyProperties.class)娉ㄨВ鏉ュ惎鐢ㄩ厤缃睘鎬х殑娉ㄥ叆銆?/p>
闄や簡杩欎簺鏂规硶锛岃繕鍙互浣跨敤@PropertySource
娉ㄨВ銆?code>@Configuration娉ㄨВ绛夋柟寮忔潵璇诲彇閰嶇疆鏂囦欢銆傚叿浣撲娇鐢ㄥ摢绉嶆柟寮忥紝鍙栧喅浜庝綘鐨勯渶姹傚拰涓汉鍋忓ソ銆?/p>
相关问答