我们先看看在servlet中怎么调用ejb3: public class HelloServlet extends GenericServlet { private Hello _hello;
public void setHello(Hello hello) { _hello = hello; }
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { PrintWriter out = res.getWriter(); out.println(_hello.hello()); } } 然后我们看看xml中的配置方法: <web-app> <servlet servlet-name="hello" servlet-class="com.hongsoft.HelloServlet"> <init hello="_ejb.HelloBean.HelloBean__EJB"/> </servlet> </web-app> 我们看到了什么?配置文件中把HelloBean传给了setHello作为参数,当然,HelloBean实
现了Hello接口;service中,直接调用_hello.hello(),实际调用的是HelloBean的
hello()方法实现. 呵呵,通过set方法来将需要的HelloBean传递给servlet,如果我们的需求发生了改变,
新加了Hello2Bean实现,我们只需要在配置文件中进行修改就可以了,这,就是ioc模式
中的type2. Spring Framework采用的也是type2的ioc模式,比如spring配置文件如下: <beans> <bean id=“studentType1" class=“com.hongsoft.test.StudentType1"/> <bean id=“teacher“ class=“com.hongsoft.test.Teacher"> <property name=“student"> <ref bean=“studentType1"/> </property> </bean> </beans> 那么我们在代码中就可以这么使用: public class Teacher {
private Student student;
public void setStudent(Student student) { this.student = student; } //写论文方法 public void writePaper() { student.writePaper(); } } 这样,如果要写IOC的论文,就找一个精通IOC的学生写;如果要写BPEL的论文,就找一个
精通BPEL的学生写,要修改的地方,也就是配置文件而已.

|