Spring Boot读取配置文件
1)通过注入ApplicationContext 或者 Environment对象来读取配置文件里的配置信息。
package com.ivan.config.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
@Autowired
ApplicationContext context;
@Autowired
Environment environment;
@RequestMapping(value="/config", method={RequestMethod.GET})
public String getConfigContent(){
String name = context.getEnvironment().getProperty("db.user.name");
return name;
}
@RequestMapping(value="/configEnv", method={RequestMethod.GET})
public String getConfigEnvironment(){
String name = environment.getProperty("db.user.name");
return name;
}
}
2)通过@ConfigurationProperties配合@PropertySource读取配置文件里的配置信息。
1:通过@PropertySource指定当前类里属性的配置文件地址,ConfigurationProperties可以指定