我有一个Spring Boot应用程序问题。
该应用程序使用saml与其他服务器进行通信。因此,我有一个带有组件注释的类,可以从自定义属性文件(而不是application.properties)读取一些属性,以获取诸如url之类的通信信息。
我不允许发布真实代码,所以这是伪代码中的示例。
@Component
public class A implements ConfigInterface {
@Value ("${placeholder1 from properties-File}")
private ... value1;
@Value ("${placeholder2 from properties-File}")
private ... value2;
...
}
用法的控制器如下所示:
@Controller
public class controller {
@Autowired
private ConfigInterface config;
public method ( ... ) {
...
createAMessage(config);
...
}
}
我的任务是将A类复制到B类中,并从其他属性文件中加载相似的属性。
这里再次是一个例子:
@Component ("classAProperties")
public class A implements ConfigInterface {
@Value ("${placeholder1 from properties-File1}")
private ... value1;
@Value ("${placeholder2 from properties-File1}")
private ... value2;
...
}
@Component ("classBProperties")
public class B implements ConfigInterface {
@Value ("${placeholder1 from properties-File2}")
private ... value1;
@Value ("${placeholder2 from properties-File2}")
private ... value2;
...
}
用法:
@Controller
public class controller {
@Autowired
@Qualifier("classAProperties")
private ConfigInterface configA;
@Autowired
@Qualifier("classBProperties")
private ConfigInterface configA;
public methodA ( ... ) {
...
createAMessage(configA);
...
}
public methodB ( ... ) {
...
createAMessage(configB);
...
}
}
问题是,如何告诉A类仅从properties-file1加载属性,而B类仅从properties-file2加载属性?我试图在类A和B中都使用@ PropertiesSource-annotation,但最后它总是在控制器的两种方法中都使用类B的属性。
编辑:
这两个属性文件都在资源文件夹中。
属性文件如下所示:
propertiesA.properties
placeholder1 = URL for destination
placeholder2 = Path to keystore
...
propertiesB.properties
placeholder1 = URL for other destination
placeholder2 = Path to other keystore
...
最佳答案
您可以按以下方式使用@ConfigurationProperties
,
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="props.a")
public class A implements ConfigInterface {
private ... value1;
private ... value2;
//getters setters
}
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="props.b")
public class B implements ConfigInterface {
private ... value1;
private ... value2;
//getters setters
}