`
yangzb
  • 浏览: 3494676 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Using Spring with EJB 3

阅读更多

Using Spring with EJB 3

By Robert. Filed in Java   |  
Tags: ejb , ioc , spring

TOP  del.icio.us digg

Back when we were planning the migration to Glassfish, I realised we would have two dependency-injection frameworks in use – EJB 3 and Spring. For obvious reasons, I wanted to know more about how these would interact. At the time (last July), I couldn’t find anyone who had used EJB 3 and Spring together – even Ben Alex from Interface21 hadn’t come across it. Six months later, and I still haven’t heard of anyone using Spring _from_ EJBs. Except for us.


There’s lots of reasons to use both EJB 3 and Spring. EJBs have benefits Spring doesn’t give – integration with things like Servlets and JSP tags, better integration with the container for monitoring and management, tool support, and so on. Spring has benefits as well – most notably, you don’t need the container, but also you get more control over the bean lifecycle. Together, they are a good complement.

But how do you get a Spring-managed bean from an EJB? The answer: dependency injection, of course. That is, with the aid of a EJB Interceptor:

[source='java']
public class SpringBeanInterceptor {

private BeanFactory beanFactory;

@PostConstruct public void configureSpringBeans(InvocationContext context) throws Exception {
for (Method method : context.getTarget().getClass().getMethods()) {
if (method.isAnnotationPresent(SpringBean.class)) {
Class springClass = method.getParameterTypes()[0];
String springName = determineSpringBeanName(method, springClass);
Object springBean = beanFactory().getBean(springName);
try {
method.invoke(context.getTarget(), springBean);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
}
context.proceed();
}

private String determineSpringBeanName(Method method, Class springClass) {
String springName = method.getAnnotation(SpringBean.class).value();
if (springName.length() > 0) {
springName = toCamelCase(springClass.getSimpleName());
}
return springName;
}

private String toCamelCase(String string) {
return Character.toLowerCase(string.charAt(0)) + string.substring(1, string.length());
}

private BeanFactory beanFactory() {
if (beanFactory == null) {
BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(”classpath*:beanRefContext.xml”);
BeanFactoryReference ref = locator.useBeanFactory(”applicationContext-service”);
beanFactory = ref.getFactory();
}
return beanFactory;
}
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SpringBean {
String value() default “”;
}
[/source]

That’s it. This Interceptor will look over an EJB, after it’s created, and provides the Spring beans. This version looks for ’setter-methods’ with an @SpringBean annotation (you could also change it to look for fields), and looks up a corresponding bean from the Spring context (the ContextSingletonBeanFactoryLocator makes this possible).

Here’s how you would use it:

[source='java']
@Stateless
@Interceptors(SpringBeanInterceptor.class)
public class MyServiceBean implements MyService {
private MySpringBean bean;

@SpringBean public void setMySpringBean(MySpringBean bean) {
this.bean = bean;
}
}
[/source]

With this (and one other trick I’ll discuss soon), you can (nearly) seamless integrate EJB3 and Spring.

The one big limitation of this: with Stateless Session Beans, you can only inject stateless dependencies, and you can only inject them when the EJB is initialised.

分享到:
评论

相关推荐

    Using Spring with JDO and Hibernate 中文版

    在众多的持久化框架和技术中,JDO(Java Data Objects)作为一种非EJB的标准,提供了一种轻量级的数据持久化解决方案。本文旨在介绍如何将Spring框架与JDO结合起来使用,实现应用的透明持久性,并通过具体的实例展示...

    Spring Recipes: A Problem-Solution Approach, Second Edition

    * Spring enterprise: Spring Java EE integration, Spring Integration, Spring Batch, jBPM with Spring, Spring Remoting, messaging, transactions, scaling using Terracotta and GridGrain, and more. ...

    pro Spring

    Learn how to replace common EJB features with Spring alternatives, including Spring's comprehensive AOP-based transaction management framework. Learn to integrate and use these other open source ...

    Agile.Java.Development.with.Spring.Hibernate.and.Eclipse-part3

    Agile Java™ Development With Spring, Hibernate and Eclipse is a book about robust technologies and effective methods which help bring simplicity back into the world of enterprise Java development....

    Agile.Java.Development.with.Spring.Hibernate.and.Eclipse

    Agile Java™ Development With Spring, Hibernate and Eclipse is a book about robust technologies and effective methods which help bring simplicity back into the world of enterprise Java development....

    Java.EE.Development.with.Eclipse.2nd.Edition.178528534

    Develop, debug, test, and ... Creating Web Applications with Spring MVC Chapter 9. Creating Web Services Chapter 10. Asynchronous Programming with JMS Chapter 11. Java CPU Profiling and Memory Tracking

    spring dm in action sample chapter6

    For example, when using JPA with OSGi, developers need to set up the persistence unit in a way that it can be dynamically managed by the OSGi framework. #### Creating OSGi Bundles from Existing Java...

    Rapid Java Persistence and Microservices

    在描述中提到的“Persistence Made Easy Using Java EE8, JPA and Spring”强调了通过使用Java EE8和JPA以及Spring框架来实现数据持久化的便捷性。这表明,本书可能会详细讲解如何利用这些技术简化数据库操作和数据...

    XDoclet in Action

    - **Integration with Frameworks**: Examples of integrating XDoclet with popular web frameworks like Struts and Spring. #### Chapter 5: XDoclet and Web Frameworks Building on the previous chapter, ...

    JAVA架构设计原则与J2EE必读书目推荐

    7. **《XML and Java: A Practical Guide to Using XML with Java for Data Exchange and Web Services》**:这本书讲解了如何使用Java处理XML数据,包括解析、生成、验证和转换XML文档的方法。 8. **《Patterns of...

    java视频教程Day01 免费

    3. Expression and Flow Control (表达式和流控制) 4. Array (数组) 5. Object-Oriented Programming I (类与对象I) 6. Object-Oriented Programming II (类与对象II) 7. Object-Oriented Advanced Topic (类与...

    Android-networking-1

    - Spring、Hibernate/JPA、EJB3、GWT、Hadoop、SOAP 和 RESTful Web Services 等高级主题也是课程内容的一部分。 在进行安卓网络编程教学和学习的过程中,要注重实践操作,因为理论知识与实际应用的结合非常重要。...

    J2EE学习笔记(J2ee初学者必备手册)

    第四章 Working with Reusable Components(重用的组件)..241 JavaEE@xuxiang 4 Java/JavaEE学习笔记Jonny xuxiang5612@sina.com 第五章 Handling Exceptions(异常的处理)243 第六章 Advanced Topics(高级主题).........

    Java/JavaEE 学习笔记

    第四章 Working with Reusable Components(重用的组件)..241 第五章 Handling Exceptions(异常的处理)243 第六章 Advanced Topics(高级主题)..........243 第七章 Custom Tags(自定义标记) .246 第八章 EL元素...

    Maven权威指南 很精典的学习教程,比ANT更好用

    EJB 10.2.5. WAR 10.2.6. EAR 10.2.7. 其它打包类型 10.3. 通用生命周期目标 10.3.1. Process Resources 10.3.2. Compile 10.3.3. Process Test Resources 10.3.4. Test Compile 10.3.5. Test 10.3.6. ...

Global site tag (gtag.js) - Google Analytics