You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 8 SE与Jersey中替换@Dependent和@ApplicationScoped注解方案咨询

Handling @Dependent and @ApplicationScoped in Java 8 SE + Jersey

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 @Singleton annotation: This is part of the JSR-330 dependency injection spec (which Jersey supports via HK2). Just swap @ApplicationScoped with @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 @Singleton is 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-hk2 with your Jersey version). This enables the DI functionality needed for @Singleton and the default per-lookup behavior.
  • If the original Java EE example uses other CDI-specific features (like @Produces or @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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:25:19