EJB: Inject a Singleton with @Startup

Introduction

Keywords

a @Singleton with @Startup bean. Example:

@Startup
@Singleton
class StartupClass {
  public void myPublicMethod() { 
    // do something
  }
  @PostConstruct
  void onStart() { }

  @PreDestroy
  void onStop() { }
}

Problem

with @Inject, I got a Wildfly dependency error:

"WELD-001408: Unsatisfied dependencies for type ..."

How to solve it?

Common

Create an interface with @Local over @Singleton class

// Interface ...
@Local
interface StartupLocalInterface {
  public void myPublicMethod();
}

Declare the interface

@Startup
@Singleton
class StartupClass implements StartupLocalInterface {
  public void myPublicMethod() { 
    // do something
  }
  @PostConstruct
  void onStart() { }

  @PreDestroy
  void onStop() { }
}

1st approach

  1. see Common aboce
  2. @Inject the interface
    @Stateless
    public class MyBean {
      // ...
      @Inject
      StartupLocalInterface startupClass;
      // ...
    }
    

2nd approach

  1. see Common above
  2. On top of class StartupClass, add an @EJB declaration:
     @EJB(name="startupClass", beanInterface=StartupLocalInterface.class)
  3. use a context lookup
    try {
        Context ctx = new InitialContext();
        StartupLocalInterface t = 
          (StartupLocalInterface) ctx.lookup("java:comp/env/startupClass");
        // do the job...
    } catch (NamingException e) {
        e.printStackTrace();
    }