java - 如何使用spring加载基于服务器环境的属性文件以便可以注入(inject)值?

标签 java spring

令我惊讶的是,我很难找到这个问题的答案。我见过很多例子,你可以使用@PropertySource 来为一个类加载一个特定的属性文件。我还看到了一些示例,您可以在其中轻松地在 Spring Boot 项目中添加不同的属性文件。但是我想要做的是为一个不是 spring boot 的 spring 项目执行此操作并加载一个属性文件,以便可以将该文件的值注入(inject)到使用 @Component 注释的类中,这取决于服务器环境。因此,例如,如果我在开发服务器上,我希望加载一个特定的属性文件,而在生产环境中则需要一个不同的属性文件。我这样做的原因是因为我的数据和服务层是它们自己的模块。这些模块包含自己的单元测试,可以在其他 Spring Boot 项目中作为自己的模块导入。我需要加载属性文件来为这些使用 spring 但不使用 spring boot 的模块提供服务。我尝试了以下方法,但这不起作用。

@Configuration
@Profile("test")
@EnableJpaRepositories("com.hi.repository")
@EnableTransactionManagement
@EnableScheduling
public class InfrastructureConfig  {
...
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        Map<String, String> env = System.getenv();
        String propertiesFile=null;

        String e = env.get("SERVER_ENV");

        if (e.equals("dev")) {
            propertiesFile = "environment/development.properties";
        } else if (e.equals("prod")) {
            propertiesFile = "environment/production.properties";
        }

        configurer.setLocation(new ClassPathResource(propertiesFile));


        return configurer;

    }

然后我有一个看起来像这样的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/DealServiceTest-context.xml"})
@ActiveProfiles("test")
public class LogTest {

    private static final Logger log = LogManager.getLogger(LogTest.class);

    @Autowired
    PathsService pathsService;

    @Autowired
    Environment environment;


    @Test
    public void testBeans(){
        System.out.println("********** WASSUP from LogTest");
        System.out.println(environment.getProperty("imageBucket"));

    }

虽然测试打印出 null ,这表明属性文件尚未加载并准备好注入(inject)其值。我怎样才能做到这一点?

最佳答案

您实际上并不需要自己设置属性,但您可以使用 spring 配置来完成。查看文档:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

如果您使用的是 spring boot - 您需要做的就是为您的环境创建多个属性文件。并且仅适用于您需要覆盖的属性。

所以你的主要属性文件将在

src/main/resources/application.properties

生产

src/main/resources/application-prod.properties

发展

src/main/resources/application-dev.properties

测试

src/main/resources/application-test.properties

然后只需使用配置文件名称作为您的环境变量

java -jar -Dspring.profiles.active=prod demo-0.0.1-SNAPSHOT.jar

关于java - 如何使用spring加载基于服务器环境的属性文件以便可以注入(inject)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46081338/

相关文章:

java - IncationTargetException 尝试创建服务类的新实例

java - AlphaComposite Transparency 重绘重叠成黑色

java - 我无法使用 itext (xmlWorker) 读取 h1 标签 pdf

java - If语句在android中不断激活

java - StringBuilder 和 StringBuffer 的区别

java - Hibernate用俄语创建记录显示为问号mysql

当实现 AsyncConfigurer 时,Spring 异步不起作用

java - Spring Security - 在哪里设置默认用户的权限?

java - 在intellij中创建SQLite数据库

spring - H2 SQL语法异常