如何在Spring中注入静态属性?

时间:2012-11-26 17:32:13

标签: spring spring-mvc multilingual

我正在尝试使用一些静态方法和属性创建一个实用程序类,问题是这些属性应该从messages.properties文件中加载,用于多语言porpouse。

我想我应该使用MessageSourceAware但是如何保持方法静态?我迷路了..

而且,我如何获得Locale?我们正在使用SessionLocaleResolver,但我认为在jsp中会自动加载。我怎样才能在课堂上得到它?

[谢谢,我在春天很新]


我会尝试更好地解释一下。

我的课程定义为

public MyClass {
    protected static final MY_PROP = "this is a static property";

    protected static String getMyProp() {
        return MY_PROP;
    }
}

我想从我的messages.properties文件中注入MY_PROP,具体取决于Locale,如

public MyClass {
    protected static final MY_PROP = messageSource.getMessage("my.prop", locale);

    protected static String getMyProp() {
        return MY_PROP;
    }
}

这可能是soomehow吗?

2 个答案:

答案 0 :(得分:2)

您是否考虑过尝试使用MethodInvokingFactoryBean

OR 您可以通过为applicationContext.xml注入一个静态属性来获得一些帮助: -

 <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="de.inweb.blog.BadDesign.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

答案 1 :(得分:0)

好的,最后我实现了MessageSourceAware,删除了静态引用并注入了我的类。

类似于:

public MyClass implements MessageSourceAware {
    // this is automatically injected by Spring
    private MessageSource messageSource;
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
    // ###################

    protected String getMyProp(Locale locale) {
        return messageSource.getMessage("my.prop", null, locale);
    }
}

并且在我的Rest服务中,由于RequestMapping,Spring会自动注入Locale。我还注入了整个类以避免静态方法。

@Controller
public class Rest {

    @Autowired
    private MyClass myClass;

    @RequestMapping(method = RequestMethod.POST, value="/test", headers="Accept=application/json")
    public String myMethod(Locale locale) {
        return myClass.getMyProp(locale);
    }
}

这是有效的。 :)

相关问题