2010-02-17 77 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文件。