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;
    }
...

 

上一篇:MyEclipse 从数据库反向生成Hibernate实体类


下一篇:Cookie和Session