axis2 Web service. Where to put my own configuration
I have written a Web Service in Java using axis2 and the POJO deployment (to a Tomcat server). My service opens a connection to a MySQL database. To do that, I need the connection string. Where do I put the connection string, so I don't have to hard code it into the code? And how do I access it from code? I would like to set th开发者_JAVA百科is parameter somewhere on the service level, not globally for the whole server. Is this possible?
You could use tomcat to configure the DB connectivity for you and then just look up the javax.sql.DataSource using JNDI.
Have look at these for tomcat:
JNDI resources
JNDI datasource example
Using JNDI would also mean that you automatically become a little more compatible in case you ever need to move to a different web container/app server.
If you want to use a config file, you can place one at the following location:
axis2/WEB-INF/services/classes/config-file.xml
You can access this file in code using the AxisService classloader, which is available during the startUp(ConfigurationContext configctx, AxisService service) method. startUp() is fired when your service is started (either post-deployment or after a container restart).
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
}
During the init(ServiceContext serviceContext)
method of your service implementation class, you can get access the database connection created during ServiceLifeCycle.startUp()
via the ServiceContext.getAxisService().getParamterValue()
method.
Note: You must specify the ServiceLifeCycle implementation class in the your service's services.xml
file, as the class
attibute of the service
tag:
<!-- 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>
With this approach, your config file is held outside of the aar
file. The benefit is you can promote the same aar
file through different test environments, picking up the relevant settings for each environment in the environment specific config file. Additionally you can edit the config file without having to open up the aar
file.
精彩评论