【问题标题】:Set attributes of ServletContext in Spring 3.2 MVC configurationSpring 3.2 MVC配置中设置ServletContext的属性
【发布时间】:2013-12-07 12:48:49
【问题描述】:

我被困在一个非常简单的任务上:如何在 Spring MVC 3.2 配置中设置 ServletContext 属性?

我发现可以使用 ServletContextPropertyPlaceholderConfigurer 完成类似的操作,但从 Spring 3.1 开始,这被视为已弃用:
已弃用。在 Spring 3.1 中支持 PropertySourcesPlaceholderConfigurer 和 StandardServletEnvironment。”

这并没有告诉我太多,因为我不知道如何使用 StandardServletEnvironment。

有什么建议吗?

【问题讨论】:

    标签: java spring servlets spring-mvc


    【解决方案1】:

    您可以为此使用ServletContextAttributeExporter。在您的配置文件中定义一个ServletContextAttributeExporter bean,如下所示,并将其attributes 属性设置为您要放入ServletContextkey and value 对的映射:

    <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
        <property name="attributes">
            <map>
                <entry key="myKey" value="1" />
            </map>
        </property>
    </bean>
    

    【讨论】:

    • 正是我需要的!谢谢
    • 您能否提供代码如何使用纯 java 配置完成?以及如何获取jsp中的属性?
    【解决方案2】:
    1. 在类路径的某处创建一个 *.properties 文件,例如/myprops.properties
    2. 将属性占位符添加到您的上下文配置中:

      &lt;context:property-placeholder location="myprops.properties"/&gt;

    或者,如果您使用的是 java config:

    @Configuration
    @PropertySource("classpath:myprops.properties")
    public class ApplicationConfiguration {
        ...
    }
    

    【讨论】:

    • 当你的意思是“context-config”时,application-context.xml 对吗?
    • 谢谢。一旦我将&lt;context:...&gt; 放入application-context.xml,再加上@PropertySource("classpath:myprops.properties"),我可以通过@Value() 获取myprops.properties 的内容以进行文件I/O?
    • @user75782131 不是“加号”,如果您使用的是 xml-config,请使用 &lt;context:..;如果您使用的是 Java-config,请使用 @PropertySource。在这两种配置样式中,您都可以在此之后使用@Value。顺便说一句:使用@Value 时,您还可以指定在prop-source 中找不到属性时使用的默认值:如果找不到属性hfs.datastore@Value("${hfs.datastore:/var/opt/datastore/hfs}") String datastore) 将使用/var/opt/...
    猜你喜欢
    • 2014-12-25
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2018-01-20
    • 1970-01-01
    • 2013-01-14
    相关资源
    最近更新 更多