我已经使用Spring框架创建了一个SDK,该SDK将被使用
与REST后端集成,以利用依赖项注入。

在这个SDK中,我有MapPropertySources来处理PropertyPlaceHolders
基本上我以编程方式在其中注册一些我想要的属性
将在SDK中使用@Value批注进行解析。

它可以在SDK中正常运行,但是当我构建SDK(使用构建器)时
Spring-boot应用程序中,来自MapPropertiesPlaceHolder的属性
不再解决。

我有来自builder类的这段代码:

    public MyRepository build() {


    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext();

    StandardEnvironment env = new StandardEnvironment();
    context.setEnvironment(env);


    Map<String, Object> propertiesMap = new HashMap<>();
    propertiesMap.put("baseUrl", baseUrl);

    MutablePropertySources mutablePropertySources = context.getEnvironment().getPropertySources();
    mutablePropertySources.addFirst(new MapPropertySource("customPropertiesMap", propertiesMap));


    if(jerseyClient == null){
        jerseyClient = JerseyClientBuilder.createClient();
    }

    context.getBeanFactory().registerSingleton("jerseyClient", jerseyClient);

    context.setParent(null);
    context.register(MySdk.class);
    context.refresh();

    MySdk mySdk = new MySSdk(context);

    return mySdk;
}

这就是实例化SDK并创建新的方式
里面的Spring上下文。

问题是MapPropertySource中的属性
当我将SDK用作另一个的Maven依赖项时,无法解决spring-boot应用程序。这可能与父母有关
上下文?属性尚未解析...我应该在哪里进行调查?

长话短说,我已经在SDK的测试中解决了@Value('${baseUrl})的问题,但是当我将此SDK包含在另一个spring-boot应用程序中时,将不再解决它。为什么?

编辑:
MySdk类如下所示:
@ComponentScan
@Service
@PropertySource("classpath:application.properties")
public class DeviceRepository {

    private ApplicationContext context;

    public MySdk(){
    }

    public MySdk(ApplicationContext context) {
        this.context = context;
    }
    // other methods that calls beans from context like
    // this.context.getBean(MyBean.class).doSomething()

在同一SDK中的测试中,一切工作正常。的baseUrl属性可以很好地解析,但是当我将此SDK连接到另一个
弹簧应用程序,在构建器中传递的属性,不是
@Value注释识别。

最佳答案

您是否在Spring配置中定义了PropertySourcesPlaceholderConfigurer bean?每当@Value批注内的属性解析失败时,这就是想到的第一件事。

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

链接到Javadoc:

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html

09-10 09:15
查看更多