概念理解
EJB是sun的服务器端组件模型,设计目标与核心应用是部署分布式应用程序。凭借java跨平台的优势,用EJB技术部署的分布式系统可以不限特定的平台。定义了一个用于开发基于组件的企业多重应用程序的标准。
企业Bean
在J2EE中,Enterprise Java Beans(EJB)称为Java 企业Bean,是Java的核心代码,分别是会话Bean(Session Bean),实体Bean(Entity Bean)和消息驱动Bean(MessageDriven Bean)。
企业Bean
1.Session Bean:有状态和无状态
有状态的会话Bean:即Ejb能够为同一个客户端在多次请求方法调用之间保持状态信息。
无状态的会话Bean:EJB容器不会对EJB的状态做管理,容器会使用实例池的方式或者单例的方式来实现无状态的SessionBean
由:Struts2中的Action,是有状态(prototype);Spring管理的业务逻辑类,是无状态的(Singleton)
这篇博客挺好:有状态sessionbean无状态sessionbean
2.Entity Bean:是持久数据组件,代表存储在外部介质中的持久(Persistence)对象或者已有的企业应用系统资源。简单地讲,一个Entity Bean可以代表数据库中的一行记录,多个客户端应用能够以共享方式访问表示该数据库记录的Entity Bean。
3.MessageDriven Bean是基于JMS消息,一种异步的无状态SessionBean。
JMS下一篇将详细介绍。
EJB的依赖注入:
第一:通过JNDI来获取HelloWord
public interface Jndi {
public String sayHello();
}
@Stateless
@Remote( { Jndi.class })
@RemoteBinding(jndiBinding = "com/wkc/jndi")
public class JndiBean implements Jndi {
@Override
public String sayHello() {
HelloWorld helloworld = getHelloWorld();
return helloworld.sayHello("jndi");
}
public HelloWorld getHelloWorld() {
try {
InitialContext ctx = new InitialContext();
HelloWorld helloworld = (HelloWorld) ctx
.lookup("com/wkc/helloworld");//通过jndi来获取HelloWorld
return helloworld;
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
}
第二:通过@Ejb()注释来存取HelloWord
public interface Injection {
String sayHello();
}
第一种方式:
@Stateless
@Remote( { Injection.class })
@RemoteBinding(jndiBinding = "com/wkc/injection")
public class InjectionBean implements Injection {
@EJB(beanName="HelloWorldBean")//beanName指定EJB的名称(如果@Stateless或@Stateful没有设置过name属性,默认为不带包名的类名)
private HelloWorld helloworld;
@Override
public String sayHello() {
return helloworld.sayHello("注入者");
}
}
第二种方式:
@Stateless
@Remote( { Injection.class })
@RemoteBinding(jndiBinding = "com/wkc/injection")
public class InjectionBean implements Injection {
private HelloWorld helloworld;
@EJB(beanName = "HelloWorldBean")//容器会在属性第一次使用之前,自动的用正确的参数调用bean的Setter方法
public void setHelloWorld(HelloWorld helloworld) {
this.helloworld = helloworld;
}
@Override
public String sayHello() {
return helloworld.sayHello("注入者");
}
}
第三种方式:
@Stateless
@Remote( { Injection.class })
@RemoteBinding(jndiBinding = "com/wkc/injection")
public class InjectionBean implements Injection {
@EJB(mappedName="com/wkc/helloworld")//mappedName指定EJB的全局JNDI名
private HelloWorld helloworld;
@Override
public String sayHello() {
return helloworld.sayHello("注入者");
}
}