将EJB 3注入到Spring Bean中

6

我已经用Spring和Spring Security制作了一个Mavenized Web应用程序...现在,我想添加EJB模块来访问数据库,我在互联网上搜索了一下,但因为这是我第一次使用EJB,所以没有找到清晰的答案。我想在我的控制器中使用类似于@EJB的东西。

@Stateless(name = "CustomerServiceImpl")
public class CustomerServiceImpl implements CustomerService 


@EJB
private MyEjb myEjb;

如何在Spring上下文中配置它,如果有教程或其他帮助,请告诉我。这将非常好,谢谢。

2个回答

5
为了将您的EJB 3 Bean注入Spring Bean,您可以按照以下步骤进行操作: 1. 创建您的Spring Bean 2. 创建带有其远程和本地接口的EJB 3. 编写实现类 例如:
package com.ejb;
@Local
public interface MyEjbLocal{
       public String sendMessage();
}

package com.ejb;
@Remote
public interface MyEjbRemote{
       public String sendMessage();
}

@Stateless(mappedName = "ejb/MessageSender")
public class MyEjbImpl implements MyEjbLocal, MyEjbRemote{
 public String sendMessage(){
   return "Hello";   
 }
}

以下是使用远程和本地接口的EJB3示例:

现在我们创建Spring Bean,其中注入此EJB。

package com.ejb;

@Service
public class MyService {

   private MyEjbLocal ejb;

   public void setMyEjbLocal(MyEjbLocal ejb){
        this.ejb = ejb;
  }

  public MyEjbLocal getMyEjbLocal(){
       return ejb;
  }
}

我们已经在Spring中添加了EJB实例,但是我们需要将其注入到Spring的spring-config.xml文件中。 有两种方法可以将EJB注入到Spring bean中:
  1. 第一种方式:
<bean id ="myBean" class="org.springframework.ejb.access.LocalStetelessSessionProxyFactoryBean">
       <property name="jndiName" value="ejb/MessageSender#com.ejb.MyEjb=Local />
       <property name="businessInterface" value="com.ejb.MyEjbLocal" />
</bean>

注意:我在这里使用了Local接口,您可以根据自己的需要使用Remote接口。

  1. 另一种注入EJB的方式是:
<jee:remote-slsb id="messageSender"
jndi-name="ejb/MessageSender#com.ejb.MyEjbLocal"
           business-interface="com.ejb.MyEjbLocal"
           home-interface="com.ejb.MyEjbLocal"
           cache-home="false" lookup-home-on-startup="false"
           refresh-home-on-connect-failure="true" />

当Bean被初始化时,EJB将会注入到你的Spring Bean中。


第一种方法对我有效!谢谢!但是请注意,第一个示例中的LocalStatelessSessionProxyFactoryBean拼写错误。我不得不面对ClassNotFoundException一段时间,直到我意识到这个问题。 - Adrián Paredes

3
请看这里:http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#ejb-access-local 您可以使用setter注入来注入EJB。请按照以下方式配置您的bean:
<bean id="myComponent" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
    <property name="jndiName" value="ejb/myBean"/>
    <property name="businessInterface" value="com.mycom.MyComponent"/>
</bean>

<bean id="myController" class="com.mycom.myController">
    <property name="myComponent" ref="myComponent"/>
</bean>

您可以使用<jee:local-slsb>标签来注入您的EJB:
<jee:local-slsb id="myComponent" jndi-name="ejb/myBean"
        business-interface="com.mycom.MyComponent"/>

<bean id="myController" class="com.mycom.myController">
    <property name="myComponent" ref="myComponent"/>
</bean>

1
我尝试过这个,但jboss一直告诉我找不到jndi名称...所以我把它删除了,然后只用了@EJB,一切都正常工作了!!!这样正确吗?注意:我的war文件使用ejb模块作为依赖项。 - elpazio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接