user972276
user972276

Reputation: 3053

dynamically create new object with Spring properties injected

I want to create Foo objects on the fly, but I want one of Foo's fields to be filled in by a property value defined by Spring's xml file.

For instance, I have the following Foo class:

public class Foo {
    @Value("${val1}")
    private String val1;

    private String val2

    public foo(String val2) {
        this.val2 = val2;
    }

    public String getVal1(){
        return val1;
    }

    public void setVal1(String val1) {
        this.val1 = val1;
    }
}

Now, I know that the @Value will come as null because my Foo object is not defined as a bean in my XML file. But, I do not want to define it as a bean as I need to define val2 dynamically like so:

Foo foo = new Foo("val2");

Is there a way to inject val1 into every instance of Foo that is created? I know the new operator is outside the scope of Spring and therefore cannot inject the value, but I am mainly looking for any way to dynamically specify val2 in a new instance of Foo while also injecting val1 with Spring.

Upvotes: 0

Views: 929

Answers (2)

maru2487
maru2487

Reputation: 1

There is a way to inject val1 into every new Instance of Foo that is created. The value for val1 can be injected directly through the spring context.

Here's what I mean

public class Foo {

private String val1;

private String val2

public foo(AbstractApplicationContext springContext, String val2) {
    this.val2 = val2;
    this.val1 = springContext.getEnvironment().getProperty("val1");
}

public String getVal1(){
    return val1;
}

public void setVal1(String val1) {
    this.val1 = val1;
}
}

What we have done above is to pass the context through the constructor in order to get the property value.

This need not be implemented the exact way that it has been specified above. We just need to make sure that Foo has access either to the ApplicationContext or the Environment. As long as foo has access to either the ApplicationContext or the Environment, we can always pull the property value out and use it to construct Foo.

Upvotes: 0

hasnae
hasnae

Reputation: 2173

You can use AutowireCapableBeanFactory. Quote from javadoc:

Integration code for other frameworks can leverage this interface to wire and populate existing bean instances that Spring does not control the lifecycle of.

Upvotes: 1

Related Questions