简体   繁体   English

如何在EJB3中注入Spring bean?

[英]How to inject a Spring bean in an EJB3?

I'm trying to access a Spring bean in an EJB3 but it doesn't seem to get injected because I'm getting a NullPointerException. 我正在尝试访问EJB3中的Spring bean,但似乎没有注入,因为我收到了NullPointerException。

I think I'm not understanding the role of beanRefContext.xml and how it's used very well. 我认为我不了解beanRefContext.xml的作用以及如何很好地使用它。

The following EJB and XMLs are in a services JAR that resides in the WEB-INF/lib of a WAR. 以下EJB和XML位于WAR的WEB-INF / lib中的服务JAR中。 The Spring bean (the DAO) is in a separate JAR also in WEB-INF/lib. Spring bean(DAO)也位于WEB-INF / lib中的单独JAR中。

EJB : 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 : 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 : 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>

EDIT 编辑

I read the post "Inject Spring beans into EJB3" and now I added a context-param to web.xml but the problem remains. 我阅读了“将Spring bean注入EJB3中”一文 ,现在我向web.xml添加了一个context-param,但是问题仍然存在。

web.xml : web.xml

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

I apparently need more help and explanation. 我显然需要更多帮助和解释。

您可能已经注意到,但是如果万一您错过了, beanRefContext.xml需要将beanRefContext.xml作为参数传递给您的services-context.xml ,但是在您的代码中缺少它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM