Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
HJacco opened this issue Dec 18, 2023 · 0 comments

Comments

@HJacco
Copy link

HJacco commented Dec 18, 2023

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);
                }
            }
        }
    });
}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant