Spring Boot无法加载PropertySourceLoader

4

使用spring boot版本1.2.3(也测试了1.2.5),我正在遵循创建Spring Boot中自定义Jasypt PropertySourceSpring Boot & Jasypt简化:保持敏感属性加密,使用自定义PropertySourceLoader使用jsypt库。我的源加载器类在api.jar中,并且这个jar文件包含在myapplication.war文件中。这个war被部署在tomcat中。

似乎在应用程序启动时,spring没有加载EncryptedPropertySourceLoader。有人可以帮忙吗?

以下是我的项目结构和相关代码。

Project - api.jar
    | src
    | | main
    |   | java
    |     | EncryptedPropertySourceLoader.java
    |   | resources
    |     | META-INF
    |       | spring.factories

api.jar是使用api.jar!META-INF/spring.factories构建的。

package com.test.boot.env;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;

public class EncryptedPropertySourceLoader implements PropertySourceLoader, PriorityOrdered {

    private static final Logger logger = LoggerFactory.getLogger(EncryptedPropertySourceLoader.class);


    public EncryptedPropertySourceLoader() {
        logger.error("\n\n\n***CREATING properties loader.\n\n\n");
    }

    @Override
    public String[] getFileExtensions() {
        return new String[] { "properties" };
    }

    @Override
    public PropertySource<?> load(final String name, final Resource resource, final String profile) throws IOException {
        logger.error("\n\n\n***Loading properties files.\n\n\n");

        if (true) {
            throw new RuntimeException("calling load"); \\intentional to identify the call
        }
        return null;
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}

spring.factories文件包含以下内容:

org.springframework.boot.env.PropertySourceLoader=\
com.test.boot.env.EncryptedPropertySourceLoader

我也尝试过不使用'\',但没有任何区别。

以下是myapplication.war文件中spring.factories的路径。

myapplication.war!WEB-INF/lib/api.jar!META-INF/spring.factories

根据我的理解,在启动时应该看到RuntimeException,但是我的应用程序成功启动了。有人可以帮忙找出我漏掉了什么吗?

你可以使用这个库:jasypt-spring-boot,唯一需要做的就是添加一个maven依赖(jasypt-spring-boot-starter)并在运行应用程序时通过系统属性提供解密密钥。 - Ulises
谢谢@Ulises,你能指导我一下,我在上面提到的设置中有什么错误吗? - amique
1个回答

2
据我所知,工厂PropertySourceLoaderSpringFactoriesLoader 机制仅用于PropertySourcesLoader,后者仅用于加载应用程序属性。这些属性可以是application.propertiesapplication.ymlapplication.yaml文件。因此,对于您的示例,只需将一个application.properties文件添加到类路径中,就会得到您所期望的异常。
我不知道的是,为什么其他属性源导入机制(例如使用注释@PropertySource)没有经过PropertySourcesLoader以利用工厂装载程序和覆盖机制。

我已经在类路径中有application.properties文件,并且它们被正确加载。 - amique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接