简体   繁体   English

在SpringBoot的@PropertySource中指定value属性

[英]Specifying value attribute in @PropertySource in SpringBoot

SETUP 设定

I have one jar (say its A) which adds another jar (say its B) as its dependency through Maven . 我有一个罐子(比如说它的A),它添加了另一个罐子(比如说它的B)作为通过Maven依赖关系。 Jar A is from Spring Boot Application. Jar A来自Spring Boot Application。

ISSUE 问题

I have properties file in jar B under its path src/conf/. 我在jar B的路径src / conf /下有属性文件。 Am trying to set the path value in the value attribute of @PropertySource in one of java file in jar B. When trying to do it, it refers the src/conf of jar A. How can i achieve this. 我正在尝试在jar B的一个java文件中的@PropertySource的value属性中设置路径值。尝试执行此操作时,它引用jar A的src / conf。我如何实现这一点。

@PropertySource( value = { "file:${spring.profiles.path}other-services-dev.properties" })

Here spring.profiles.path gets its value from the deployment script of jar A 在这里, spring.profiles.path从jar A的部署脚本中获取其值。

Use "classpath:" instead of file: . 使用“类路径:”代替file:

Make the property file a resource of jar B by moving it to src/main/resources . 通过将属性文件移动到src/main/resources使其成为jar B的src/main/resources Then you can reference the file like this: @PropertySource("classpath:/other-services-dev.properties") . 然后,您可以像这样引用文件: @PropertySource("classpath:/other-services-dev.properties")

The better approach, which has better encapsulation, would be to define a class in jar B, which is annotated @PropertySource("classpath:/other-services-dev.properties") , and exposes the properties through getters. 更好的封装方法是在jar B中定义一个类,该类被@PropertySource("classpath:/other-services-dev.properties")注释,并通过getter公开这些属性。 Then jar A can simply let this class be injected. 然后jar A可以简单地让此类注入。

In jar B: 在罐子B中:

 @PropertySource("classpath:/other-services-dev.properties")
 @Service
 class BProperties
   @Value("${setting1}")
   private String setting1;

   public String getSetting1() {
     return setting1;
   }
 }

In jar A 在罐子A中

@Service
class SomeService {
  @Autowired
  private BProperties properties;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM