1、定义接口与实现类
// Service接口
public interface Service {
void execute();
}
// Service的实现类
public class MyService implements Service {
@Override
public void execute() {
System.out.println("MyService 执行了.");
}
}
2、自定义ioc容器以绑定接口与实现类
import java.util.HashMap;
import java.util.Map;
public class IoCContainer {
private Map<Class<?>, Object> components = new HashMap<>();
public <T> void register(Class<T> componentClass, T component) {
components.put(componentClass, component);
}
public <T> T resolve(Class<T> componentClass) {
if (components.containsKey(componentClass)) {
return (T) components.get(componentClass);
} else {
throw new RuntimeException("Component not found: " + componentClass.getName());
}
}
}
3.使用:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication
public class DemoLfsunStudyCustomiocApplication {
// public static void main(String[] args) {
// SpringApplication.run(DemoLfsunStudyCustomiocApplication.class, args);
// }
public static void main(String[] args) {
IoCContainer container = new IoCContainer();
container.register(Service.class, new MyService());
Service service = container.resolve(Service.class);
service.execute();
}
}
类似于之前IOC - Google Guice