我有Book.class
:
public class Book{
private String title;
public String getTitle() {
if(title == null){
title = "not found";
}
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
services.xml
用于配置Web服务:
<service name="StockQuoteService">
<Description>
Please Type your service description here
</Description>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass">sample.StockQuoteService</parameter>
</service>
当我启动网络服务时,我想设置新书名并获得此标题。但是当我得到这个新头衔时,我总是null
。这是因为每次发送请求时都会创建Books类的实例。如何配置此Web服务:set title Hello
并获得标题Hello
?
的StockQuoteService:
package sample;
public class StockQuoteService {
private Book book = new Book();
public void setBook(Book book){
this.book = book;
}
public String getTitle(){
return book.getTitle();
}
}
答案 0 :(得分:0)
为避免每次都创建新对象,您必须在Axis2中使用LifeCycle并将Book实例存储在Axis2 Context中。按照以下步骤进行操作。
不要在StockQuoteService类中创建新的Book实例。只需将变量声明为
即可private Book book;
更改StockQuoteService类以实现axis2的生命周期接口(org.apache.axis2.service.Lifecycle)。
通过以上更改,您必须在您的课程中实现以下两种方法。
public void init (ServiceContext serviceContext){
ConfigurationContext configurationContext =
MessageContext.getCurrentMessageContext()
.getConfigurationContext();
if (configurationContext != null) {
book = new Book();
configurationContext.setProperty("SERVICE_BOOK", book);
}
}
public void destroy(ServiceContext serviceContext) {
}
通过执行此操作,它不会在每次服务调用时创建新的Book实例。相反,它将在服务启动时创建Book实例(仅在服务启动时调用init方法),并将book变量存储在配置上下文中。