google / guice

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 11 and above, brought to you by Google.
https://github.com/google/guice
Apache License 2.0
12.51k stars 1.67k forks source link

Implement a functionality similar to Spring Boot’s fully automatic configuration dependency injection #1784

Open HJacco opened 11 months ago

HJacco commented 11 months ago

I want to implement a fully automatic configuration feature similar to Spring Boot based on the Guice framework. The static method, ‘Run’, is the application main entry point, similar to Spring Boot’s ‘SpringApplication.run’ method. This method mainly does two things: it scans all classes with the ‘@Service’ annotation under a specific package, and it configures these classes in an ‘AbstractModule’. During the implementation process, I encountered a problem: I cannot bind the interface information obtained through reflection to the corresponding implementation class. Can you provide me with some guidance? My implementation code: image `public static Injector run(Class<?> mainClass, String[] args) { String[] packages = getScanPackages(mainClass);

    final Set<Class<?>> clazzSet = new HashSet<>();
    for (String pkg : packages) {
        clazzSet.addAll(list(pkg));
    }
    if (CollectionUtils.isEmpty(clazzSet)) {
        return Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                super.configure();
            }
        });
    }

    return Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            for (Class<?> clz : clazzSet) {
                Class<?>[] interfaces = clz.getInterfaces();
                if (interfaces.length == 0) {
                    bind(clz).in(Scopes.SINGLETON);
                } else if (interfaces.length > 0) {
                    bind(interfaces[0]).to(clz).in(Scopes.SINGLETON);
                }
            }
        }
    });
}`