Phoenix
Phoenix

Reputation: 8933

How to assign a constructor-arg value of a property in a spring bean based on the enum constant

I have an enum ContentType and it has a method like ContentType.getName() which can evaluate to regText OR session. So, how do I do the below where I can instantiate the bean based on the return value of this method. Also, I only want to do this in XML config and not annotations.

<property name="contentCaptureRegEx" ref="${ContentType.getName()}">
</property>

<bean id="regText" class="java.util.regex.Pattern" factory-method="compile" lazy-init="true">
<constructor-arg value="xyz" /></bean>

<bean id="session" class="java.util.regex.Pattern" factory-method="compile" lazy-init="true">
<constructor-arg value="abc" /></bean>

Upvotes: 0

Views: 597

Answers (1)

John Watts
John Watts

Reputation: 8885

I would suggest a static factory method since the pattern regexes are already using that pattern. Just eliminate them and add:

package com.mine;

public class MyFactory {

    public static Pattern newContentCaptureRegEx() {
        String patternString;
        if ("regText".equals(ContentType.getName())) {
            patternString = "xyz";
        } else if ("session".equals(ContentType.getName())) {
            patternString = "abc";
        } else {
            throw new IllegalStateException("ContentType must be regText or session");
        }
        Pattern.compile(patternString);
    }

}

which you can wire as:

<bean id="ContentCaptureRegEx" class="com.mine.MyFactory"
    factory-method="newContentCaptureRegEx" />

And then you can ref that bean anywhere as:

<property name="contentCaptureRegEx" ref="ContentCaptureRegEx" />

Upvotes: 1

Related Questions