RoD
RoD

Reputation: 464

inject default values into Spring bean with annotation

I'd like to set default values for a list in a bean using annotations.

For example, if it's not a list you can do:

@Value("myValue")
String test;

But, in my case i want to give default values for a List of String.

List<String> tests;

In XML, it's something like that:

<bean id="beanId" class="class...">
    <property name="tests">
        <list>
            <value>value 1</value>
            <value>value 2</value>
            <value>value 3</value>
        </list>
    </property>
</bean>

I wanted to know if there is an existing annotation, or if I have to create one ?

Thank you

Upvotes: 3

Views: 7710

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

@Value understands expression language, so you can use arbitrary method calls, although the syntax may get ugly, something like this:

@Value("#{T(java.util.Arrays).asList('Value 1','Value 2','Value 3')}")

Reference:

Upvotes: 7

axtavt
axtavt

Reputation: 242686

You can assign default values directly, without any annotations:

String test = "myValue";

List<String> tests = Arrays.asList("value 1", "value 2", "value 3");

@Value is needed when you want Spring to handle values in the same way as in XML file, for example, to evaluate SpEL expressions, resolve placeholders, etc. If you don't need it, you can do assign default values without annotations.

Upvotes: 4

Related Questions