【问题标题】:Handling Context In Spring在 Spring 中处理上下文
【发布时间】:2016-02-23 16:59:56
【问题描述】:

我正在做一个小项目,我正在寻找一种在春季处理上下文的好方法。我发现自己创建了一个上下文持有者类来使用 setter 注入来保存我的属性。我遇到的问题是我正在抓取一个上下文对象并传递它。我正在寻找一种设计模式或可以帮助我以更清洁的方式做到这一点的东西。作为一个简单的例子,假设我目前正在做类似下面的事情,其中​​字段是通过 setter 注入来注入的,我正在寻找一种更好的方法来注入属性另外,假装我有大量的属性,太大了干净地使用@Value 之类的东西:

public class MyContext{

    private String configItem1;
    private String configItem2;
    private String configItem3;


    public void setConfigItem1(String configItem1){
        this.configItem1 = configItem1;
    }

    public void setConfigItem2(String configItem2){
        this.configItem2 = configItem1;
    }

    public void setConfigItem3(String configItem3){
        this.configItem3 = configItem1;
    }

}

示例弹簧上下文:

<bean id="appProperties"
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:my-app.properties</value>
            </list>
        </property>
    </bean>


<bean id="myContext" class="these.are.not.the.droids.you.are.looking.for.context.MyContext" >
     <property name="configItem1" value="${some.item.1}" />
     <property name="configItem2" value ="${some.item.2}"/>
     <property name="configItem3" value="${some.item.3}" />
</bean>

【问题讨论】:

    标签: java spring spring-mvc design-patterns properties-file


    【解决方案1】:

    如果您的配置值特定于某个请求,那么您可以使用 ThreadLocal (API for ThreadLocal),它可以在“调用上下文”中跨层保存值。您可以在控制器中填充此 ThreadLocal 变量,并在同一调用链中的任何层使用它。

    如果您的设置适用于所有请求,那么您可以使用 ApplicationContext 来存储这些值。您可以在 Spring 中像这样访问 ApplicationContext -

    @Autowired
    private ApplicationContext appContext;
    

    【讨论】:

      【解决方案2】:

      您是否考虑过简单地使用 Map 来存储值? Java 本质上是一种冗长的语言。所以我想你别无选择。 http://www.java2s.com/Tutorial/Java/0417__Spring/FillMap.htm

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-27
        • 2019-01-10
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        相关资源
        最近更新 更多