2015-08-31 250 views
1

使用,我们发现这个想法:EJB如何使用弹簧引导bean?

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/ejb.html#ejb-implementation-ejb3

我们想利用拦截器,以便从一个EJB的访问春天开机豆。但问题是,文档的示例使用了新的上下文。

EJB如何访问spring引导上下文?

我们尝试这样做:

public class MySpringActuatorMetricsCoreTestInterceptor extends SpringBeanAutowiringInterceptor { 

     //Spring boot application context 
    @Autowired 
    ApplicationContext applicationContext; 

    @SuppressWarnings("resource") 
    @Override 
    protected BeanFactory getBeanFactory(Object target) { 
     return applicationContext.getAutowireCapableBeanFactory(); 
    } 

} 

而且EBJ看起来是这样的:

// ejb 
@Stateless 
// spring 
@Interceptors(MySpringActuatorMetricsCoreTestInterceptor.class) 
public class FirstBean { 
[...] 

的问题是:应用程序上下文尚未初始化,因为EJB的初始化之前并因此发生了 - >空指针异常。

我们认为有两种选择: - 我们从弹簧引导中获得应用程序上下文。 - 我们可以将MySpringActuatorMetricsCoreTestInterceptor创建的上下文提供给Spring引导上下文。

有没有解决方法?另外一个选择?

我们使用的是GlassFish 3.1

谢谢!

+0

EJB和Spring Boot似乎与我正交。我的首选是Spring和Spring Boot。抛弃EJB。 – duffymo

+0

我还没有找到方法,最好的办法可能是将服务作为使用弹簧靴和弹簧休息的休息服务。 然而,在春季引导消费ejbs是可能的。 – werner

回答

2

好,我找到了一种方法,因为它似乎: 我只是增加了一个beanRefContext.xml到我的类路径: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans_2_0.dtd"> <beans> <bean class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg value="classpath*:simpleContext.xml" /> </bean> </beans>

引用名为simpleContext.xml一个新的applicationContext文件也是在我的类路径:

... 
<!-- Enable annotation support within our beans --> 
<context:annotation-config/> 
<context:spring-configured/> 
<context:component-scan base-package="your.package.path" /> 
<context:property-placeholder location="classpath*:*.properties" /> 

...

现在我能注入春天引导服务进我的EJB:

@Stateless(name = "RightsServiceEJB") 
@Remote 
@Interceptors(SpringBeanAutowiringInterceptor.class) 
public class RightsServiceEJB implements IRightsServiceEJB { 

    @Autowired 
    ExampleService exampleService; 

    @Override 
    public String sayHello() { 
     return exampleService.sayHello(); 
    } 

}

然而,这是现在一个小型的Hello World示例,我不知道如果弹簧服务仍可以参考由Spring启动初始化资源。这需要我的进一步测试。

+0

好吧我只是评估这种方法对使用数据库的服务,它似乎工作,该服务仍然访问我的数据库并返回一个正确的值。 – werner

+0

好吧,你必须为你的弹簧启动应用程序添加整个组件扫描。然后,Spring引导会再次启动ejb基础架构和自己的应用程序上下文。这样配置就通过ejb和应用程序实例共享。但是,您必须记住,您现在正在运行的应用程序中处理两个单独的应用程序上下文,一个用于主应用程序,另一个用于ejbs。 – werner