【问题标题】:How to inject spring properties into wicket components?如何将弹簧属性注入检票口组件?
【发布时间】:2016-03-28 19:30:39
【问题描述】:

我正在寻找将在 spring 上下文中定义的属性(由 propertiesFactoryBean 提供)注入检票口组件的可能性。我知道使用 @SpringBean-Annotation 将 bean 注入组件的方式,但是属性的对应方式是什么?

我的属性的定义方式:

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

我尝试过的事情。它的工作方式通常与自定义 bean 一起使用:

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

使用propertiesFactory的名字来访问属性值

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

使用注解

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

使用 SpringBean

@SpringBean(name="myPropertiesFactory.mySpringProperty")

这些解决方案都不起作用。因此,为了获得 mySpringProperty 注入,我使用解决方法来创建一个 String 类型的 bean,当我用 SpringBean 注释组件的相应成员时,该 bean 由 wicket 正确注入,但我认为必须有更好的解决方案。

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

注释

@SpringBean
private String mySpringPropertyBean;

【问题讨论】:

    标签: spring properties dependency-injection wicket


    【解决方案1】:

    @SpringBean 只支持 spring bean 的注入。我想有人可以实现一个 @SpringValue 注释来做你想做的事,但据我所知,没有人做过。

    我通常做的是:

    • 我的 wicket 应用程序类是 spring bean。
    • 它具有带有 @Value 注释的属性 - 因为对象是一个 spring bean,所以这些属性会被正确评估和设置
    • 我通过调用 MyApplication.get().getXXX() 或 ((MyApplication)getApplication()).getXXX() 来访问实际值
    • 如果应用程序增长并且属性数量接近限制,我会将它们重构为单独的 Settings 或 Config 类 - 每个都是它自己的 spring bean,可从应用程序类访问。

    【讨论】:

    • 这是推荐的方式!
    【解决方案2】:

    在您的 Wicket 类中使用 @Value("${mySpringProperty}"):

    @SpringBean
    private PropertiesConfiguration propertiesConfiguration;
    

    创建一个新的 PropertiesConfiguration 类:

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

    在您的检票口类中使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      相关资源
      最近更新 更多