JAVA CDI 學習(5) - 如何向RESTFul Service中注入EJB實例


RESTFul Service中如果要注入EJB實例,常規的@Inject將不起作用,在Jboss中,應用甚至都啟動不起來(因為@Inject注入失敗),解決方法很簡單:將@Inject換成@EJB

參考代碼:

CityInvoker是一個Stateless的EJB

package test;

import javax.ejb.Stateless;
import ...

@Stateless
public class CityInvoker {

    public CityResponse getCity() {
        CityResponse cityResponse = null;
        CityService cityService = ApplicationContextUtils.getCityService();
        try {
            cityResponse = cityService.findCityByCode(RequestBuilder
                    .buildCityFindRequest());
        } catch (LMSException e) {
            e.printStackTrace();
        }
        return cityResponse;
    }
...

 

下面是在RESTFul Service中注入的示例:

package test.rest;

import javax.ejb.EJB;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;


@Path("/")
public class TestService {

    final String XMLNS_NAMESPACE = "http://yjmyzz.cnblogs.com/rest/service";
    final String ROOT_NODE = "root";

    @EJB
    CityInvoker cityInvoker;

    @GET
    @Path("/findCity")
    @Produces(MediaType.APPLICATION_XML)
    public JAXBElement<CityDto> findCity() {
        JAXBElement<CityDto> result = new JAXBElement<CityDto>(new QName(
                XMLNS_NAMESPACE, ROOT_NODE), CityDto.class, cityInvoker
                .getCity().getCities().get(0));
        return result;
    }
...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM