Mabi
Mabi

Reputation: 441

How to inject spring properties into wicket components?

I'm searching for a possibility to inject a property which is defined in a spring context (provided by a propertiesFactoryBean) into a wicket component. I know the way to inject beans into components by using the @SpringBean-Annotation, but whats the corresponding way for properties?

The way my property is defined:

<bean id="myPropertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="properties">
        <props>
            <prop key="mySpringProperty">mySpringProperty</prop>
    </property>
</bean>

Things I've tried. The way it works usually with self defined beans:

@Inject
@Value("${mySpringProperty}")

Using the name of the propertiesFactory to access the property value

@Inject
@Value("$myPropertiesFactory.properties.mySpringProperty")

Using the Value Annotation

@Value("#myPropertiesFactory['mySpringProperty']")

Using SpringBean

@SpringBean(name="myPropertiesFactory.mySpringProperty")

None of these solutions works. So to get mySpringProperty injected i use the workaround to create a bean of the type String which get's injected properly by wicket when i annotate the corresponding member of my component with SpringBean but i think there must be a better solution.

<bean id="mySpringPropertyBean" class="java.lang.String">
    <constructor-arg type="java.lang.String" value="https://foobar.com" />
</bean> 

Annotate

@SpringBean
private String mySpringPropertyBean;

Upvotes: 2

Views: 1290

Answers (2)

VZoli
VZoli

Reputation: 602

In your Wicket class use instead of @Value("${mySpringProperty}"):

@SpringBean
private PropertiesConfiguration propertiesConfiguration;

Create a new PropertiesConfiguration class:

@Component
public class PropertiesConfiguration {
    @Value("${mySpringProperty}")
    private String mySpringProperty;

    //getters & setters
} 

Use in your wicket class:

System.out.println("mySpringProperty=" + propertiesConfiguration.getMySpringProperty());

Upvotes: 1

cserepj
cserepj

Reputation: 926

@SpringBean only supports injection of spring beans. I suppose someone could implement a @SpringValue annotation that does what you want, but as far as I know noone ever did.

What I usually do is:

  • My wicket application class is a spring bean.
  • It has properties with @Value annotations - as the object is a spring bean, these are evaluated and set properly
  • I access the actual values by calling MyApplication.get().getXXX() or ((MyApplication)getApplication()).getXXX()
  • If the app grows and the number of attributes approach a limit, I refactor them into separate Settings or Config classes - each one a spring bean of it's own, accessible from the application class.

Upvotes: 2

Related Questions