我想控制 web.xml 中的设置,并为不同的环境使用不同的一次。
是否可以在 web.xml 中使用类路径上的属性文件中的属性?像这样的东西:
<context-param>
<param-name>myparam</param-name>
<param-value>classpath:mypropertyfile.properties['myproperty']</param-value>
</context-param>
最好的祝福
磷
我想控制 web.xml 中的设置,并为不同的环境使用不同的一次。
是否可以在 web.xml 中使用类路径上的属性文件中的属性?像这样的东西:
<context-param>
<param-name>myparam</param-name>
<param-value>classpath:mypropertyfile.properties['myproperty']</param-value>
</context-param>
最好的祝福
磷
不可以。但是,您可以将属性文件传入并在运行时从中读取。
<context-param>
<param-name>propfile</param-name>
<param-value>myprop.properties</param-value>
</context-param>
如果您有权访问 servlet,那么在运行时加载属性就很简单了。
Properties properties = new Properties();
GenericServlet theServlet = ...;
String propertyFileName = theServlet.getInitParameter("propfile");
properties.load(getClass().getClassLoader().getResourceAsStream(propertyFileName));
Object myProperty = properties.get("myProperty");
如果使用不同的环境,您很可能不会在运行时从一个环境切换到另一个环境,因此不需要使用属性文件。
如果使用 maven,您可以为您的环境定义不同的配置文件,并在每个配置文件中设置要更改的参数。
在你的 pom.xml
<profile>
<id>env1</id>
<properties>
<my.param>myParamValue<my.param/>
</properties>
</profile>
<profile>
<id>env2</id>
<properties>
<my.param>myParamValue2<my.param/>
</properties>
</profile>
在你的 web.xml
<context-param>
<param-name>myparam</param-name>
<param-value>${my.param}</param-value>
</context-param>
并在 Maven 战争插件中的部署描述符中配置过滤
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
</configuration>
</plugin>
AFAIKcontext-param
两者env-entry
都持有静态值。您不会从属性文件中获取运行时(动态)值。它会像:
<context-param>
<param-name>myparam</param-name>
<param-value>myactualpropertyvalue</param-value>
</context-param>
对值的任何更改都需要重新部署 Web 应用程序。
在您的示例中,您检索的值将是 Stringclasspath:mypropertyfile.properties['myproperty']
如果您使用 Glassfish,您可以从命令行即时更新它http://javahowto.blogspot.com/2010/04/glassfish-set-web-env-entry.html
如果我了解您的要求是在构建时(即不同环境的不同战争)而不是在运行时?
您可以在 ant/maven 构建过程中替换 web.xml 中的值。