google / google/guice

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

Open
#1,784 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

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](https://github.com/google/guice/assets/11569147/0465a8c1-7af8-476e-90cc-6140f9e85427)
`public static Injector run(Class mainClass, String[] args) {
String[] packages = getScanPackages(mainClass);

final Set> 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);
}
}
}
});
}`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.