Java 8 SE与Jersey中替换@Dependent和@ApplicationScoped注解方案咨询
Hey there! Since you're working with Java 8 SE and Jersey instead of Java EE 6, those CDI annotations (@Dependent and @ApplicationScoped) won't work out of the box—Java SE doesn't include the CDI spec by default. Here's how to replace them properly:
Replacing @ApplicationScoped
@ApplicationScoped marks a class as a singleton that lives for the entire app lifecycle. For Jersey in Java SE, you have two solid options:
- Use Jersey's built-in
@Singletonannotation: This is part of the JSR-330 dependency injection spec (which Jersey supports via HK2). Just swap@ApplicationScopedwith@javax.inject.Singleton. Jersey will ensure only one instance of your class exists across the entire application. - Manual singleton pattern: If you prefer not to use DI, implement a classic singleton (like the double-checked locking pattern) for your class. That said, using
@Singletonis more idiomatic with Jersey's ecosystem.
Replacing @Dependent
@Dependent means a new instance is created every time the class is injected or requested. Good news—this is Jersey's default behavior for classes without a scope annotation! So you can simply remove the @Dependent annotation entirely, and Jersey will automatically create a new instance each time it's needed, matching the original @Dependent behavior.
Key Notes
- Make sure you have the Jersey HK2 dependency in your project (e.g., for Maven, add
org.glassfish.jersey.inject:jersey-hk2with your Jersey version). This enables the DI functionality needed for@Singletonand the default per-lookup behavior. - If the original Java EE example uses other CDI-specific features (like
@Producesor@Qualifier), you'll want to replace those with their JSR-330 or Jersey equivalents to keep things working smoothly in Java SE.
内容的提问来源于stack exchange,提问作者Vova Chornyi

