---
title: "spring web.xml中设置变量"
author: "dbp_cn"
date: "2018-04-26T11:13:07Z"
tags: []
categories: ["Web前端"]
slug: "spring-web-xml"
draft: false
lastmod: "2018-04-26T11:13:07Z"
id: 2420217
url: "https://dbp5588.iteye.com/blog/2420217"
---

1\. spring web.xml注入系统配置属性(如app.properties).

因为web.xml是web系统的配置入库，代码一经编译之后web.xml里面的值就不可改变，不能再程序运行时替换。所以如果需要在web.xml配置属性变量，必须在编译的时候就将属性变量替换。

具体需要在项目新建不同环境的属性文件

 

如(开发文件application-development.properties，测试application-integratetest.properties，生产application-production.properties)。然后在pom文件里面利用mavn profile 指定针对不同环境替换对于的属性文件里的变量，

如下例中有下面变量需要

```
<filter>
    <filter-name>CAS Authentication Filter</filter-name>
    <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
    <init-param>
      <param-name>casServerLoginUrl</param-name>
      <param-value>${uuc.host}/login</param-value>
    </init-param>
    <init-param>
      <param-name>serverName</param-name>
      <param-value>${server.name}</param-value>
    </init-param>
    <init-param>
      <param-name>gateway</param-name>
      <param-value>false</param-value>
    </init-param>
```

  

 1. 在application-development.properties等属性文件中配置

```
uuc.host=http://172.31.52.12:2280/uuc
conf.dir=classpath:
server.name=http://172.31.66.161:4000
```

 2.在项目的pom.xml 中配置如下build 参数

```
<build>
	<finalName>ROOT</finalName>
	<defaultGoal>compile</defaultGoal>
	<filters>
		<filter>${filter.file}</filter>
	</filters>
        	<resources>
		<resource>
			<directory>src/main/resources</directory>
			<includes>
				<include>**/*</include>
			</includes>
			<filtering>true</filtering>
		</resource>
		<resource>
			<directory>src/main/resources/properties</directory>
			<includes>
				<include>**/*</include>
			</includes>
			
			<filtering>true</filtering>
		</resource>
	</resources>
</build>
<profiles>
    <!-- 开发 -->
    <profile>
      <id>dev</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <filter.file>src/main/resources/properties/application-development.properties</filter.file>
      </properties>
    </profile>
    <!-- 测试 -->
    <profile>
      <id>test</id>
      <properties>
        <filter.file>src/main/resources/properties/application-integratetest.properties</filter.file>
      </properties>
    </profile>
    <!-- 生产 -->
    <profile>
      <id>prod</id>
      <properties>
        <filter.file>src/main/resources/properties/application-production.properties</filter.file>
      </properties>
    </profile>
  </profiles>
```

 3. maven打包命令使用如下参数即可：

```
mvn clean install -DskipTests -Pdev (开发)
mvn clean install -DskipTests -Ptest (测试)
mvn clean install -DskipTests -Pprod (生产)
```