我正在应用程序的web.xml中定义一个上下文参数,如下所示
<context-param>
<param-name>baseUrl</param-name>
<param-value>http://www.abc.com/</param-value>
</context-param>
现在我想在我的控制器中使用baseUrl的值,那么我如何访问这个。。。。。?
如果有人知道这件事,请告诉我。
提前感谢!
如果您使用的是Spring3.1+,则无需执行任何特殊操作即可获得属性。只需使用熟悉的${property.name}语法即可。
例如,如果您有:
<context-param>
<param-name>property.name</param-name>
<param-value>value</param-value>
</context-param>
在web.xml
或中
<Parameter name="property.name" value="value" override="false"/>
在Tomcat的context.xml
中
然后你可以访问它像:
@Component
public class SomeBean {
@Value("${property.name}")
private String someValue;
}
这是因为在Spring3.1+中,部署到Servlet环境时注册的环境是StandardServlet环境,它将所有与Servlet上下文相关的属性添加到始终存在的Environment
中。
让您的控制器实现Servlet上下文感知接口。这将强制您实现一个setServletContext(ServletContext servletContext)
方法,Spring将在其中注入Servlet上下文。然后只需将Servlet上下文引用复制到一个私有类成员。
public class MyController implements ServletContextAware {
private ServletContext servletContext;
@Override
setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
您可以通过以下方式获取参数值:
String urlValue = servletContext.getInitParameter("baseUrl");
首先,在您的Spring应用程序"applicationContext.xml"(或任何您命名的名称:)中,添加一个属性占位符,如下所示:
<context:property-placeholder local-override="true" ignore-resource-not-found="true"/>
如果您也想加载.properties文件中的一些值,则可以添加可选参数"location"。(例如,location="WEB-INF/my.properties")。
需要记住的重要属性是'local-override="true"'属性,它告诉占位符在加载的属性文件中找不到任何内容时使用上下文参数。
然后,在构造函数和setter中,您可以使用@Value注释和SpEL(Spring Expression Language)执行以下操作:
@Component
public class AllMine{
public AllMine(@Value("${stuff}") String stuff){
//Do stuff
}
}
该方法还有一个额外的好处,就是从Servlet上下文中抽象出来,并使您能够在属性文件中用自定义值覆盖默认上下文参数值。
希望能有所帮助:)