Suggested Pages

Thursday, April 30, 2015

Inject Stateless EJB in a Web Listener - Example

ParentRepository.java


package com.javablog.entity;

import javax.ejb.Local;

@Local
public interface ParentRepository {

void save(Parent parent);

}

ParentRepositoryBean.java


package com.javablog.entity;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless(name="ParentRepositoryBean")
public class ParentRepositoryBean implements ParentRepository {

 @PersistenceContext(name="exampleUnit")
 private EntityManager entityManager;
 
 
 @Override
 public void save(Parent parent){
  entityManager.persist(parent);
 }
}

MyContextListener.java


package com.javablog.entity;

import javax.ejb.EJB;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyContextListener implements javax.servlet.ServletContextListener {
 
 @EJB 
 private ParentRepository parentRepository;
 
 public void contextInitialized(ServletContextEvent sce) {
  Parent parent = new Parent();
  parent.setName("John");
  parent.setId(1);
  parentRepository.save(parent);
 }

 public void contextDestroyed(ServletContextEvent sce) {
 }
}

No comments :

Post a Comment

Suggested Pages