【问题标题】:How to inject a Spring bean in an EJB3?如何在 EJB3 中注入 Spring bean?
【发布时间】:2013-06-22 09:33:53
【问题描述】:

我正在尝试访问 EJB3 中的 Spring bean,但它似乎没有被注入,因为我得到了 NullPointerException。

我想我不是很了解 beanRefContext.xml 的作用以及它是如何使用的。

以下 EJB 和 XML 位于服务 JAR 中,该 JAR 位于 WAR 的 WEB-INF/lib 中。 Spring bean(DAO)在一个单独的 JAR 中,也在 WEB-INF/lib 中。

EJB

@Stateless
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class TimetrackingServiceBean implements TimetrackingService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getAllUsers() {
        return this.userDao.findAll(); // <-- NPE
    }
}

beanRefContext.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

        <bean name="serviceContext" class="org.springframework.context.support.ClassPathXmlApplicationContext"></bean>

</beans>

services-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:annotation-config />

</beans>

编辑

我阅读了"Inject Spring beans into EJB3" 的帖子,现在我在 web.xml 中添加了一个上下文参数,但问题仍然存在。

web.xml

...
<context-param>
  <param-name>parentContextKey</param-name>
  <param-value>serviceContext</param-value>
 </context-param>
...

我显然需要更多帮助和解释。

【问题讨论】:

  • 我已经阅读了那篇文章,它确实对我有帮助(我认为),但我仍然有相同的 NPE。

标签: java spring ejb-3.0


【解决方案1】:

您可能已经注意到,但如果您错过了,beanRefContext.xml 需要将您的 services-context.xml 作为 argument em>,但是您的代码

中缺少它

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2011-03-30
    • 2015-09-14
    • 2013-05-08
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多