2010-02-17 67 views
0

我寫了一個使用axis2和POJO部署(到Tomcat服務器)的Java Web服務。我的服務打開與MySQL數據庫的連接。要做到這一點,我需要連接字符串。我在哪裏放置連接字符串,所以我不必將其硬編碼到代碼中?我如何從代碼訪問它?我想在服務級別的某處設置此參數,而不是整個服務器的全局參數。這可能嗎?axis2 Web服務。在哪裏把我自己的配置

回答

1

您可以使用tomcat爲您配置數據庫連接,然後使用JNDI查找javax.sql.DataSource。

有看看這些爲Tomcat:

使用JNDI也意味着您將自動成爲一個小的情況下,你需要更多的兼容移動到不同的Web容器/應用程序服務器。

1

如果你想使用一個配置文件,您可以將一個在以下位置:

axis2/WEB-INF/services/classes/config-file.xml 

您可以在代碼中使用的AxisService類加載器訪問這個文件,它的啓動(ConfigurationContext configctx期間可用,AxisService服務)方法。啓動服務時(啓動後或啓動容器後)會啓動startUp()。

import org.apache.axis2.engine.ServiceLifeCycle; 
public class LifeCycleImpl implements ServiceLifeCycle { 

    public void startUp(ConfigurationContext configctx, AxisService service) {  

     InputStream in = service.getClassLoader().getResourceAsStream("config-file.xml"); 
     //Extract your database config from the input stream 

     //Create database connection 

     //Store the connection as a service parameter using service.AddParameter 

} 

在您的服務實現類的init(ServiceContext serviceContext)方法,你可以訪問通過ServiceContext.getAxisService().getParamterValue()方法中ServiceLifeCycle.startUp()創建的數據庫連接。

注意:您必須指定在爲您服務的services.xml文件ServiceLifeCycle實現類,爲class attibute的service標籤:

<!-- The class attribute defines the hook into the Service lifecycle methods 
startUp and shutDown --> 
<service name="YourService" class="com.macima.webservice.LifeCycleImpl"> 
    <!--Specify the web service's implementation class --> 
    <parameter name="ServiceClass">com.macima.webservice.ServiceImpl</parameter>  
    <!--Declare methods exposed by the web service--> 
    <operation name="getSomething"> 
     <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/> 
    </operation> 
    </parameter> 
</service> 

通過這種方法,您的配置文件保持外aar文件。好處是您可以通過不同的測試環境推廣相同的aar文件,爲環境特定配置文件中的每個環境提取相關設置。此外,您可以編輯配置文件,而無需打開aar文件。