【发布时间】:2010-02-17 12:35:29
【问题描述】:
我使用axis2 和POJO 部署(到Tomcat 服务器)用Java 编写了一个Web 服务。我的服务打开了与 MySQL 数据库的连接。为此,我需要连接字符串。我将连接字符串放在哪里,所以我不必将它硬编码到代码中?以及如何从代码中访问它?我想将此参数设置在服务级别的某个位置,而不是针对整个服务器全局设置。这可能吗?
【问题讨论】:
标签: java tomcat web-services axis2
我使用axis2 和POJO 部署(到Tomcat 服务器)用Java 编写了一个Web 服务。我的服务打开了与 MySQL 数据库的连接。为此,我需要连接字符串。我将连接字符串放在哪里,所以我不必将它硬编码到代码中?以及如何从代码中访问它?我想将此参数设置在服务级别的某个位置,而不是针对整个服务器全局设置。这可能吗?
【问题讨论】:
标签: java tomcat web-services axis2
您可以使用 tomcat 为您配置数据库连接,然后使用 JNDI 查找 javax.sql.DataSource。
看一下tomcat的这些:
使用 JNDI 还意味着您会自动变得更加兼容,以防您需要迁移到不同的 Web 容器/应用服务器。
【讨论】:
如果你想使用一个配置文件,你可以在以下位置放置一个:
axis2/WEB-INF/services/classes/config-file.xml
您可以使用 AxisService 类加载器在代码中访问此文件,该类加载器在 startUp(ConfigurationContext configctx, AxisService service) 方法期间可用。 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 实现类,作为service 标签的class 属性:
<!-- 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 文件即可编辑配置文件。
【讨论】: