Enterprise Java Beans (EJB)

EJB Proxy access

If you call this.myMethod() on an EJB all container managed stuff will not be invoked (e.g. transaction management).The following example shows you how to get access to your own proxy instance and start a new transaction.

@Stateless
public class MyService implements MyServiceLocal {

  @Resource
  private SessionContext sessionCtx;

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public void myMethod() {
    ...
  }

  @Override
  public void foo() {
    MyServiceLocal service = sessionCtx.getBusinessObject(MyServiceLocal.class);
    service.myMethod();
  }
}

Java Management Extensions (JMX)

Use JMX if you want to monitor or configure your enterprise application at runtime. MBeans must be singletons. Therefore you have to annotate your EJB with @Singleton.

@Singleton
@Startup
public class Monitoring implements MonitoringMXBean {

    private static final String OBJECT_NAME = "Monitoring:type="
            + Monitoring.class.getName();

    private MBeanServer mBeanServer;

    private ObjectName objectName;

    /**
     * Register instance as MXBean
     */
    @PostConstruct
    public void registerMBean() {
        try {
            objectName = new ObjectName(OBJECT_NAME);
            mBeanServer = ManagementFactory.getPlatformMBeanServer();
            mBeanServer.registerMBean(this, objectName);
        } catch (Exception e) {
            throw new IllegalStateException("Could not register MBean into JMX:" + OBJECT_NAME, e);
        }
    }

    /**
     * Unregister MXBean instance
     */
    @PreDestroy
    public void unregisterMBean() {
        if ((mBeanServer != null) && (objectName != null)) {
            try {
                mBeanServer.unregisterMBean(objectName);
            } catch (Exception e) {
                throw new IllegalStateException("Could not unregister MBean from JMX:" + OBJECT_NAME, e);
            }
        }
    }
}