IOC - 自定义IOC容器

ゝ一纸荒年。 2024-02-19 10:48 184阅读 0赞

1、定义接口与实现类

  1. // Service接口
  2. public interface Service {
  3. void execute();
  4. }
  5. // Service的实现类
  6. public class MyService implements Service {
  7. @Override
  8. public void execute() {
  9. System.out.println("MyService 执行了.");
  10. }
  11. }

2、自定义ioc容器以绑定接口与实现类

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class IoCContainer {
  4. private Map<Class<?>, Object> components = new HashMap<>();
  5. public <T> void register(Class<T> componentClass, T component) {
  6. components.put(componentClass, component);
  7. }
  8. public <T> T resolve(Class<T> componentClass) {
  9. if (components.containsKey(componentClass)) {
  10. return (T) components.get(componentClass);
  11. } else {
  12. throw new RuntimeException("Component not found: " + componentClass.getName());
  13. }
  14. }
  15. }

3.使用:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. //@SpringBootApplication
  4. public class DemoLfsunStudyCustomiocApplication {
  5. // public static void main(String[] args) {
  6. // SpringApplication.run(DemoLfsunStudyCustomiocApplication.class, args);
  7. // }
  8. public static void main(String[] args) {
  9. IoCContainer container = new IoCContainer();
  10. container.register(Service.class, new MyService());
  11. Service service = container.resolve(Service.class);
  12. service.execute();
  13. }
  14. }

类似于之前IOC - Google Guice

发表评论

表情:
评论列表 (有 0 条评论,184人围观)

还没有评论,来说两句吧...

相关阅读

    相关 IOC容器

    描述 IOC:控制反转,将对象的创建过程交给Spring容器,由容器管理对象的生命周期; Bean的作用域 Spring Bean实例的作用范围由配置