samedi 18 juin 2016

Spring two different application context - property placeholder collision

I have been created an SDK using Spring framework that will be used to integrate with a REST backend, to make use of the dependency injection.

In this SDK, I have MapPropertySources to handle PropertyPlaceHolders. Basically I register programmatically some properties there which I want to be resolved within the SDK with @Value annotation.

It works fine within the SDK, but when I build the SDK (using the builder) inside a Spring-boot app, the properties from MapPropertiesPlaceHolder are not resolved any longer.

I have this piece of code from the builder class:

    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;
}

This is the way I instantiate the SDK and I create a new Spring context inside it.

The problem is that the properties within the MapPropertySource are not resolved when I use the SDK as a maven dependency in another spring-boot application. It might have anything to do with the parent context? The properties are just not resolved... Where should I investigate?

Long problem short, I have the @Value('${baseUrl}) being resolved within the SDK's tests, but when I include this SDK in another spring-boot application, it will not be resolved anylonger. Why?

Edit:

MySdk class looks like this:

@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()

Everything works fine in the tests from within the same SDK. The baseUrl property is resolved fine, but when I wire this SDK in another spring application, the properties passed in the builder, they are not recognised by the @Value annotation.

Aucun commentaire:

Enregistrer un commentaire