简体   繁体   中英

Does Guice intentionally execute noarg methods annotated with @Inject?

I just noticed this after accidentally annotating a method with @Inject instead of @Override . Does Guice intentionally allow this or is it something that should be considered a bug?

public class GuiceExample {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(GuiceManagedResource.class);
            }
        });

        // The following is printed to the console:
        //
        // constructor
        // doSomethingUnexpected
        injector.getInstance(GuiceManagedResource.class);
    }

    static class GuiceManagedResource {
        @Inject
        GuiceManagedResource() {
            System.out.println("constructor");
        }

        @Inject
        void doSomethingUnexpected() {
            System.out.println("doSomethingUnexpected");
        }
    }
}

Injection is part of the initialization of the object. Any constructor, method or field annotated with @Inject will be processed. See the javadoc

Constructors are injected first, followed by fields, and then methods.

So, yes, if a method is found with the annotation @Inject , Guice will invoke it (following some rules).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM