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
- see Common aboce
- @Inject the interface
@Stateless public class MyBean { // ... @Inject StartupLocalInterface startupClass; // ... }
2nd approach
- see Common above
- On top of class StartupClass, add an @EJB declaration:
@EJB(name="startupClass", beanInterface=StartupLocalInterface.class)
- 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(); }