1、使用@Value注解
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class MyBean {@Value("${myapp.name}") private String appName;public void printAppName() {System.out.println(appName);}
}
2、使用Environment對象
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;@Component
public class MyBean {private final Environment environment;public MyBean(Environment environment) {this.environment = environment;}public void printConfigParam() {String paramValue = environment.getProperty("myapp.param"); System.out.println(paramValue);}
}
3、使用@ConfigurationProperties 注解
當有大量的配置參數時,可以將它們組合到一個POJO類中,并使用@ConfigurationProperties注解進行自動裝配。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "myapp") // myapp 為配置參數的前綴
public class ConfigEntity {private String name;private String param;private int version;// getters and setters...public static class InnerClass {private boolean enabled;// getter and setter for inner class properties...}private InnerClass inner;// getters and setters for inner class properties...
}
4、使用@EnableConfigurationProperties 注解
如果想要全局共享配置參數,則可以使用@EnableConfigurationProperties注解。首先創建一個與配置項對應的POJO類,并使用@ConfigurationProperties 注解指定前綴。然后,在主程序類上添加@EnableConfigurationProperties注解,并傳入該POJO類作為參數。示例如下所示:
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;@SpringBootApplication
@EnableConfigurationProperties(ConfigEntity.class)
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}