Spring Boot 獲取配置檔案application.properties的屬性值
阿新 • • 發佈:2021-02-20
技術標籤:Spring Boot 整合spring boot配置檔案Configuration屬性值java
1、實現CommandLineRunner介面,(org.springframework.boot.CommandLineRunner)
2、新增類註解:@Configuration,(org.springframework.context.annotation.Configuration)
3、通過@Autowired自動裝載介面ApplicationContext,(org.springframework.context.ApplicationContext)
4、在介面函式run中通過ApplicationContext獲取Environment,(Environment environment = applicationContext.getEnvironment();)
5、通過Environment獲取屬性值:environment.getProperty("spring.datasource.url")
程式碼示例(獲取配置檔案application.properties中server.port的值):
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @Configuration public class MyConfiguration implements CommandLineRunner { @Autowired ApplicationContext applicationContext; @Override public void run(String... args) throws Exception { Environment environment = applicationContext.getEnvironment(); String serverPort = environment.getProperty("server.port"); System.out.println("value of server.port is " + serverPort); } }
啟動spring boot即會進入到run中