Using CDI in a singleton pattern

前端 未结 2 869
时光说笑
时光说笑 2021-02-05 14:11

I\'m trying to inject a logger object in a class that is implemented following a singleton approach.

The code almost looks like this:

Logger class:<

相关标签:
2条回答
  • 2021-02-05 14:48

    Injections happens after construct. So you cant use it in the constructor.

    One way is to add a method annotated @PostConstruct that can will be invoked after injections.

    @PostConstruct
    public void init() {
        logger.info("Creating one and only one instance here!");
    }
    

    On a sidenote i Think you are aprouching the problem in the wrong way. CDI has a nice singleton support

    create a class annotated @Singleton

    @Singleton
    public class MySingleton {
    
        @Inject
        Logger logger;
    
        @PostConstruct
        public void init() {
            logger.info("Creating one and only one instance here!");
        }
    
    }
    

    Above assumes you are using CDI for java ee (JSR-299).

    If you are using JSR 330 Dependency Injection (guice etc.) link

    You could use constructor injection:

    @Singleton
    public class MySingleton {
    
    
        private final Logger logger;
    
        @Inject
        public MySingleton (Logger logger) {
            this.logger = logger;
            logger.info("Creating one and only one instance here!");
        }
    }
    
    0 讨论(0)
  • 2021-02-05 14:51

    This will not work, because injection, as already mentioned, will be performed after the constructor is called.

    Methods annotated with @PostConstruct are called after injection has been finished and before the object itself will be supplied somewhere else.

    However, injection only works if the instance of your class is provided by injection itself. This is due to the injection depending on proxying.

    Therefore you will need to inject your MySingleton wherever you need it. To be sure it is a singleton, annotate it @Singleton and the container will work that out for you.

    Addiotnally beware, that singleton in terms of CDI spec does not mean only one instantiation, but rather only one initialiation of @PostConstruct.

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