2017年4月26日 星期三

Spring - CXF 小心得

xml設定檔:
<bean id="XxxBean" class="xxx.XxxBean">

<bean id="ServiceImpl" class="xxx.ServiceImpl" />

<jaxws:endpoint id="Service" implementorClass="xxx.Service" implementor="#ServiceImpl" address="/Service">
    <jaxws:properties>
        <entry key="mtom-enabled" value="true"/>
    </jaxws:properties>
</jaxws:endpoint>


Java:
@MTOM
public interface Service {
    @WebMethod
    public Response xxxMethod();
}


@MTOM
public class ServiceImpl implements Service{
    @Autowired
    private ApplicationContext appContext;

    // 讓bean不為單例改用此寫法
    private XxxBean getXxxBean(){
        return (XxxBean)appContext.getBean("XxxBean");
    }

    @WebMethod
    public Response xxxMethod(){
        return new Response();
    }
}


1.不需要@WebService

這邊要特別註明
很多網站都會在 Java 的 Class 和 interface 上面加@WebService的標籤
其實這個是很不必要的東西
加了會造成這個 Service 有兩個接口

一個是xml檔裡設定的address="/Service"
另一個是@WebService

@WebService有細項參數可以調整,若沒給的話會使用預設值
而address就是其中一個

所以如果沒有打算要開兩個接口的話就不要加@WebService

(如果有讀者發現這段話是因為少設什麼所以才導致這種情形的話希望能回饋給我,感恩!!)

2.scope prototype

ServiceImpl在Spring-cxf的架構下每個request都是使用同一個ServiceImpl Object
這就表示ServiceImpl中使用到@Autowired的Object也會被固定為同一個Object
(無論@Autowired的Object有沒有做設定)

假設有什麼寫法必須使用不同的Object,就只好使用appContext.getBean()的方式
另外Bean要配合設定(擇其一)
XML:scope="prototype"
JAVA CLASS:@Scope("prototype")

3.MTOM

如果有用到DataHandler
在上傳到service這時的inputStream用完的話要記得close
不然會有殘檔在server上
下載會自己關,不用擔心

沒有留言:

張貼留言