在配置Tomcat源码运行时,需要配置运行参数。
其中有一个配置:
在RunAS里面,Main class 填写 org.apache.catalina.startup.Bootstrap 启动类,
然后选择 Arguments ,在 Program arguments 填写 start , 在 VM arguments 中填写 tomcat home 的路径,
如:-Dcatalina.home="D:\tomcat\apache-tomcat-6.0.37-src"
这个-D配置有什么作用呢?
当Bootstrap启动时 调用
start()→init→setCatalinaHome()
其中setCatalinaHome()代码片段如下:
private void setCatalinaHome() {
if (System.getProperty("catalina.home") != null)
return;
File bootstrapJar =
new File(System.getProperty("user.dir"), "bootstrap.jar");
if (bootstrapJar.exists()) {
try {
System.setProperty
("catalina.home",
(new File(System.getProperty("user.dir"), ".."))
.getCanonicalPath());
} catch (Exception e) {
// Ignore
System.setProperty("catalina.home",
System.getProperty("user.dir"));
}
} else {
System.setProperty("catalina.home",
System.getProperty("user.dir"));
}
}
如果 catalina.home为空的话,系统将设置默认的catalina.home。
System.setProperty
("catalina.home",
(new File(System.getProperty("user.dir"), ".."))
而这个不是我想要的。所以需要初始化一个应用系统变量,防止出错。
同时tomcat启动时也有相关配置设置(catalina.bat)如下:
rem Execute Java with the applicable properties
if not "%JPDA%" == "" goto doJpda
if not "%SECURITY_POLICY_FILE%" == "" goto doSecurity
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
goto end
这些参数都可以在项目中通过System.getProperty()方法获得。相当于一个全局的应用系统变量,随应用系统而生,终止而终止。不是环境变量。
下面一个小例子:
package test;
public class Commander {
public static void main(String[] args) {
String myProp=System.getProperty("prop.custom");
System.out.println(myProp);
}
}
在控制台,用命令行添加运行参数打出结果:
java -Dprop.custom=gobstopper Commander
结果:
gobstopper