我正在尝试从ldap-TEST.properties
文件中读取ldap属性 并尝试将其绑定到我指定的 Java 配置类。@PropertSource
并定义了属性源占位符配置器的静态 Bean。 我仍然得到无法解析占位符spring.profiles.active
值类路径:/ldap-${spring.profiles.active}.属性以下是项目文件,请帮助我
@Configuration
@PropertySource("classpath:/ldap-${spring.profiles.active}.properties")
public class LdapConfig {
@Autowired
Environment env;
@Bean
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.url"));
contextSource.setBase(env.getRequiredProperty("ldap.base"));
contextSource.setUserDn(env.getRequiredProperty("ldap.userDn"));
contextSource.setPassword(env.getRequiredProperty("ldap.password"));
contextSource.afterPropertiesSet();
return contextSource;
}
@Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSource());
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
//ldap-TEST.properties file
ldap.base=dc=example,dc=com
ldap.password=password
ldap.port=839
ldap.userDn=cn=read-only-admin,dc=example,dc=com
ldap.url=ldap://ldap.forumsys.com:389
我的主要应用程序
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
您不能在 spring 中使用 Type 注释的字符串值${spring.profiles.active}
等属性。 此类属性将被注入到属性或方法的注释中,例如@Value
。
spring.profiles.active
后面的值实际上是一个数组。因此,即使该值被正确扩展,也会出现它无法按您想要的方式工作的极端情况。
如果通过@PropertySource
配置的路径的工作方式与application.properties|yml
相同,那就太好了,但目前情况并非如此(GitHub 上有一个关于此的活动问题(。因此,必须考虑替代方案:
- 最简单的替代方法是使用常规文件名
application.properties|yml
和application-{profile}.properties|yml
.我看不出有什么好的理由不这样做,但我不知道你的项目要求,所以...... - 稍微复杂一点,使用 Java 代码获取配置的配置文件,并以编程方式配置 Spring 环境。有关更多详细信息,请参阅此SO答案。
如果您在本地计算机上运行,则只需更改属性文件名 application-default.property 即可进行临时即时工作。
对于永久解决方案,您必须检查您的项目是否在 docker 上运行:
如果在 docker 上运行,请使用以下命令:
mvn clean package -DskipTests=true && sudo docker build
sudo docker run -d -e spring.profiles.active="local" -e <other key and value of bootstrap.property file>
否则,如果在云服务器上运行,请按照以下步骤操作:
- 在引导属性文件中放置
spring.profiles.active=local
- 将应用程序文件重命名为
application-local.properties
您还可以参考:配置文档中2.3.3. Profile Specific Files
部分
我在尝试测试我的 Spring Boot 应用程序时遇到了同样的问题,这是我的解决方案,取自 https://www.baeldung.com/spring-profiles#2-using-springprofilesactive
public class AppConfig {
@Value("${spring.profiles.active:test}")
private String activeProfile;
}
@SpringBootTest
@ActiveProfiles("test")
public class TestingWebApplicationTest {
@Test
public void contextLoads() {
}
}