扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

springboot鎬庝箞璇诲彇閰嶇疆鏂囦欢

扬州沐宇科技
2023-10-24 22:33:44
springboot

鍦⊿pring Boot涓紝鍙互閫氳繃@Value娉ㄨВ銆?code>Environment鎺ュ彛銆?code>@ConfigurationProperties娉ㄨВ绛夋柟寮忔潵璇诲彇閰嶇疆鏂囦欢銆?/p>

  1. 浣跨敤@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>

  1. 浣跨敤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>

  1. 浣跨敤@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>

扫码添加客服微信