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中