以前使用PropertySource,当时使用是在controller中使用的,大概的使用是这样的,有个配置文件是config.properties
@Controller
@PropertySource("classpath:config.properties")
public class TestController(){
@Value("${db.url}")
String url;
}
现在在service中想使用配置文件,仍然这样调用,当然以前是另外一个项目,当前项目是这种情况,配置好了,加载的时候,会报错,说【${db.url}】 找不到,此路不通,后续再看原因,因为急于项目开发,根据网上的提示,用以下方式实现了:
@Configuration @PropertySource("classpath:config.properties") public class AppConfig { //这个Environment是自动注入的: @Autowired Environment env; public void testM(){ String url=env.getRequireProperty("db.url") } }
那么使用这种方式就可以正常获取值了。