Spring Bean中的EJB 3 Sessioncontext

时间:2013-03-27 23:54:50

标签: java spring java-ee ejb-3.0

背景:

我正在使用java安全性进行编程身份验证(基本身份验证)。 我有一个无状态会话bean(EJB 3)。我可以注入Sessioncontext来获取安全性Principal,以获取用户名。 在同一个项目中,我使用Spring bean作为JDBC和Aspect。我想在其中一个方面(Audit)获取用户名,这也是一个spring bean。

问题:

是否可以访问Spring bean中的ejb sesssioncontext。如果是这样怎么办? 如果不是,如何从Spring bean访问用户名,这也是一个方面。

谢谢, 阿米特

2 个答案:

答案 0 :(得分:2)

这可以通过将EJB注入spring bean来完成。您可以通过手动JNDI查找(就像在任何其他EJB客户端中一样)或使用Spring的JndiObjectFactoryBean来完成。使用Spring的JndiObjectFactoryBean:

  1. SessionContext注入EJB

    @Resource
    private SessionContext ctxt;
    //getter and setter
    
  2. 在bean配置文件中配置工厂bean。 postageService是我们感兴趣的EJBRef(从 Apress Spring Recipes 挖出的配置)

       <bean id="postageService class="org.springframework.jndi.JndiObjectFactoryBean">
             <property name="jndiEnvironment">
                <props>
                   <prop key="java.naming.factory.initial">
                        org.apache.openejb.client.RemoteInitialContextFactory
                    </prop>
                   <prop key="java.naming.provider.url">
                         ejbd://localhost:4201
                   </prop>
               </props>
             </property>
            <property name="jndiName" value="PostageServiceBeanRemote"/>
      </bean>
    
  3. 将ejb引用连接到spring bean

         public class PostalServiceClient{
    
           //wired EJB
           private PostageService service;
           //getter and setter
    
           private SessionContext retrieveSessionContext(){
               service.getCtxt(); //get the SessionContext from the EJB injection
           }
    
          } 
    

答案 1 :(得分:1)

kolossus,谢谢你的回复。 还有另一种我能找到的方法。以下是previous post的链接。所以基本上我做了完全相同的事情: 1)在spring-context xml

中添加以下行
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
    <property name="alwaysUseJndiLookup" value="true" />
</bean>

2)在我的spring bean中添加以下行以访问EJB的会话上下文

@Resource(mappedName = "java:global/TopoServices/MessageRestService!com.myrest.MessageRestService")
    private MessageRestService myBean;

重要的是Jboss 7.1不再支持自定义jndi,这与Jboss 5不同,所以我使用了默认的jndi。

我认为这是解决我的要求的更清洁方式。