Guice: how do you configure an @Provides and @Singleton in a module in this case?

后端 未结 1 1372
隐瞒了意图╮
隐瞒了意图╮ 2021-02-11 22:35

I have a provider method in a module annotated with @Provides:

@Provides
public ChatServicePerformanceMonitor getChatServicePerfMon() {
  ...
}


        
相关标签:
1条回答
  • 2021-02-11 22:46

    If you're creating the ChatServicePerformanceMonitor like this:

    @Provides
    public ChatServicePerformanceMonitor getChatServicePerfMon() {
      return new ChatServicePerformanceMonitor();
    }
    

    then your class level @Singleton annotation will have no effect because Guice isn't creating the object, you are. Guice can only enforce scope on objects it creates. There's nothing wrong with adding @Singleton to your getChatServicePerfMon() method.

    If you have a no-argument constructor (or an @Inject constructor) on the ChatServicePerformanceMonitor class and you remove your @Provides method then continual calls to the injector will return the same singleton.

    0 讨论(0)
提交回复
热议问题