简体   繁体   中英

Why Initialization is not required in EJB?

I am new to the Struts2 framework and to EJB as well. I have a class LoginDAO which implements checkUser method of an interface LoginDAOLocal . I don't understand why I see different behavior for the following scenarios:

If I use an EJB ( LoginDAO is stateless session bean) as follows, method call works perfectly without any error.

@EJB
private LoginDAOLocal loginDao;
loginDao.checkUser(userName,password);

If I use Struts2 as follows, it gives a Null pointer exception for the method call.

public class LoginAction extends ActionSupport {

    // Getters setters for userName and password)
    private LoginDAOLocal loginDao;
    loginDao.checkUser(this.userName,this.password);
}

If I use a simple Java application (no EJB or Struts2), the method call creates a compile time error saying loginDao is not initialized

public static void main(String[] args) {

    LoginDAOLocal loginDao;
    loginDao.checkUser(userName,password);
}

Can someone explain why this different behavior ?

Without getting too much into the Java EE spec: EJBs are managed by an EJB container that exists in J2EE servers (JBoss \\ Websphere etc..). The container takes control of bean lifecycle and is responsible for creating \\ destroying beans according to the application needs.

When running out of container (simple java application) your beans won't get initialized and you don't have a JNDI context to get beans from, even if you add @EJB annotation to the field member.

We can say that there are two ways to manage the beans, using the container (managed by the container), or by another component (managed by a servlet, listener or filter).

Using components managed by the container, the container injects the references. eg:

@WebServlet("/test")
public class MyServlet extends HttpServlet {

    @Resource(lookup = "jdbc/TestDS")
    private DataSource testDS;

}

By contrast, a component managed by a bean, eg:

@Namespace("/User")
@ResultPath(value = "/")
@Result(name = "success", location = "pages/login.jsp")
public class LoginAction extends ActionSupport {

}

is managed by the filter org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter . The latter should be responsible for performing dependency injection . Spring , for example, takes care of injecting all necessary dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM