首先,如果此問題的標題不正確,我很抱歉。配置jar以使用屬性管理器和tomcat從文件讀取屬性
目標:我正在使用maven打包需要讀取外部屬性文件的jar。該jar將用於將使用tomcat7部署的戰爭。在tomcat中,setenv.sh如下所示,屬性文件的位置(PROPERTY_MANAGER)是從jar中讀取屬性的位置設置的。我怎樣才能做到這一點?
我使用Apache的Tomcat的7.0.32和我setenv.sh寫着:
export JAVA_OPTS="-DPROPERTY_MANAGER=$CATALINA_HOME/myPropertiesDir -DCOMMON_PROPERTIES=$CATALINA_HOME/myCommonPropsDir -DAPP_ENCRYPTION_PASSWORD=pass $JAVA_OPTS"
在Eclipse我導入現有的Maven模塊。我的模塊在這一點上是一個簡單的java類(所以我可以測試如何通過tomcat讀取屬性)。這裏是我的課:
Class MyClass{
private String var1;
private String var2;
public MyClass(){}
public String getVar1() { return var1; }
public String getVar2() { return var2; }
public String setVar1(String a) { var1 = a; }
public String setVar2(String a) { var2 = b; }
public static void main (String []arg){
MyClass c = new MyClass();
System.out.println(「var1 = 「 + c.getVar1() +」, var2 = 「+c.getVar2());
}
}// end of class
這裏是在src /主/資源myprops.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:si=http://www.springframework.org/schema/integration
xmlns:jms=http://www.springframework.org/schema/integration/jms
xmlns:context=http://www.springframework.org/schema/context
xmlns:util=http://www.springframework.org/schema/util
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:property-placeholder location="file:${PROPERTY_MANAGER}/myclass-props.properties" ignore-unresolvable="true"/>
<!-- MyClass bean -->
<bean id="mybean" class="my.com.test.MyClass">
<property name="var1" value="${prop.var1}" />
<property name="var2" value="${prop.var2}" />
</bean>
</beans>
MyClass的道具位於$ CATALINA_HOME/myCommonPropsDir,看起來像這樣:
prop.var1=abc
prop.var2=123
上面的類被構建爲一個maven模塊並打包成jar。爲了測試這個,我啓動了tomcat,然後在Eclipse中嘗試運行主類作爲Java應用程序並將其調試爲遠程Java應用程序。遠程人不做任何事情。運行它作爲Java應用程序給我以下輸出: var1 = null,var2 = null;
很明顯屬性文件沒有被拾取。我在這裏做錯了什麼?我相信它缺少一些小東西。提前感謝所有建議。
您正在調用的主要方法不在Spring託管對象上(但創建了一個'new MyClass()'),因此它的屬性沒有被注入/初始化。 – Santosh
@Santosh不知道我關注。當我實例化類時不應該注入屬性,因此main()是否被spring管理不會是一個問題? – chapstick
當**你**實例化這個類時,你是不會使用spring的,因此不會有任何屬性注入。 – Santosh