从EJB会话Bean调用Spring Bean

时间:2014-02-16 13:28:20

标签: java spring ejb

我想从我的EJB会话Bean中调用我的Spring bean。这是我想要实现的示例场景。

Spring界面:

public interface ReqSpring {
    public String processMsg(String msg);
}

Spring Bean:

@Component
public class ReqStringImpl implements ReqSpring{

    public String processMsg(String msg) {
        return "Msg ["+msg+"] is processed";
    }
}

EJB接口:

@Remote
public interface EjbService{
    String echo(String msg);
}

EJB会话Bean:

(请注意我在Spring对象上使用了@Autowired

@Stateless(name = "EjbWS", mappedName = "EjbWS")
@WebService(name = "EjbService", portName = "EjbServicePort")
public class EjbServiceBean implements EjbService {

    =====> @Autowired
    =====> private ReqSpring reqSpring;

    public EjbServiceBean() {
    }

    @WebMethod
    public String echo(@WebParam(name="msg")String msg) {
            // This is printing null
        System.out.println("ReqSpring = "+reqSpring);
        return reqSpring.processMsg(msg);
    }
}

我的应用程序无法从EJB加载ReqSpring对象并始终生成NullPointerException。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

您无法将Spring Bean注入此EJB,因为EJB不由Spring容器管理。无论如何,通过使用SpringBeanAutowiringInterceptor,您将能够做到这一点。试试这个注释:

@Stateless(name = "EjbWS", mappedName = "EjbWS")
@WebService(name = "EjbService", portName = "EjbServicePort")
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class EjbServiceBean implements EjbService {

    @Autowired
    private ReqSpring reqSpring;

    public EjbServiceBean() {
    }

    @WebMethod
    public String echo(@WebParam(name="msg")String msg) {
        System.out.println("ReqSpring = "+reqSpring);
        return reqSpring.processMsg(msg);
    }
}