如何在Spring Controller中访问web.xml的<context-param>值

Nav*_*een 8 spring

我在我的应用程序的web.xml中定义了一个context-param,如下所示

<context-param>
    <param-name>baseUrl</param-name>
    <param-value>http://www.abc.com/</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

现在我想在我的Controller中使用baseUrl的值,所以我怎么能访问这个.....?

如果有人知道,请告诉我.

提前致谢 !

geo*_*and 9

如果您使用的是Spring 3.1+,则无需进行任何特殊操作即可获得该属性.只需使用熟悉的$ {property.name}语法即可.

例如,如果你有:

<context-param>
    <param-name>property.name</param-name>
    <param-value>value</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

web.xml

<Parameter name="property.name" value="value" override="false"/>

在Tomcat的 context.xml

然后你可以访问它像:

@Component
public class SomeBean {

   @Value("${property.name}")
   private String someValue;
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为在Spring 3.1+中,部署到Servlet环境时注册的环境是StandardServletEnvironment,它将所有与servlet上下文相关的属性添加到当前存在Environment.


Kon*_*kov 8

使Controller实现ServletContextAware接口.这将强制您实现一个setServletContext(ServletContext servletContext)方法,Spring将在其中注入ServletContext.然后只需将ServletContext引用复制到私有类成员.

public class MyController implements ServletContextAware {

    private ServletContext servletContext;

    @Override
    setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式获得参数值:

String urlValue = servletContext.getInitParameter("baseUrl");
Run Code Online (Sandbox Code Playgroud)


Pyt*_*try 5

首先,在您的 Spring 应用程序“applicationContext.xml”(或您命名的任何内容:)中,添加一个属性占位符,如下所示:

<context:property-placeholder local-override="true" ignore-resource-not-found="true"/>
Run Code Online (Sandbox Code Playgroud)

如果您还想加载在 .properties 文件中找到的一些值,可以添加“位置”的可选参数。(例如 location="WEB-INF/my.properties")。

要记住的重要属性是 'local-override="true"' 属性,它告诉占位符在加载的属性文件中找不到任何内容时使用上下文参数。

然后在您的构造函数和设置器中,您可以使用@Value 注释和 SpEL(Spring 表达式语言)执行以下操作:

@Component
public class AllMine{

    public AllMine(@Value("${stuff}") String stuff){

        //Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

此方法具有从 ServletContext 中抽象出来的额外好处,并使您能够使用属性文件中的自定义值覆盖默认上下文参数值。

希望有帮助:)