【问题标题】:Benefit of dependency injection for dynamically created objects动态创建对象的依赖注入的好处
【发布时间】:2017-10-18 22:25:32
【问题描述】:

在 IoC 容器(如 Spring)的上下文中,我正在寻找一种将一些依赖项/属性注入到类的实例化中的方法。并非对象的所有属性都可以使用依赖注入来设置,并且对象是动态创建的以响应应用程序事件。如果所有依赖项都可以通过容器注入,那么 Spring 托管 bean 将是理想的。

例如,下面定义的类必须注释为@Component(或更专业的注释),以便组件扫描和依赖注入工作。但它有几个属性(nameattempts)只能由应用程序代码而不是容器动态设置。但是如果我必须使用 endpointrestTemplate(它们已经由 IoC 容器管理),那么通过构造函数或 setter 方法将它们提供给这个对象并不方便。

public class SomeClass {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private String endpoint;

    private String name;
    private int attempts;

    public SomeClass(String name, int attempts) {

        this.name = name;
        this.attempts = attempts;
    }

    // public getter and setter methods
}

由于有一些动态设置的属性,我不能使用new 关键字来实例化类并仍然获得 DI 和 IoC 的好处。或者我可以吗?

【问题讨论】:

  • 您可以使用 AspectJ,但工厂通常是更好的选择。

标签: java spring dependency-injection


【解决方案1】:

你可以使用工厂。类似于以下内容:

public class SomeClass {

  private RestTemplate restTemplate;
  private String endpoint;
  private String name;
  private int attempts;

  public SomeClass(String name, int attempts, RestTemplate restTemplate,
      String endpoint) {
    this.name = name;
    this.attempts = attempts;
    this.restTemplate = restTemplate;
    this.endpoint = endpoint;
  }
}

@Component
public class SomeClassFactory {

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private String endpoint;

  public SomeClass create(String name, int attempts) {
    return new SomeClass(name, attempts, restTemplate, endpoint);
  }
}

SomeClass instance = someClassFactory.create("beep", 0);

【讨论】:

  • 我喜欢工厂方法。它要求我有一个冗长的 SomeClass 构造函数方法签名,但我不会直接使用该构造函数,而是使用工厂的 create 方法。
【解决方案2】:

如果我没有误解你,你需要在构造函数中设置值。

您可以从上下文创建 bean 并设置值:

context.getBean("beanname", arg1, arg2....);

【讨论】:

  • 我正在尝试确定一种无需设置/注入那些可以以某种方式直接从已由 Spring 管理的容器中注入的属性的好方法。你是说SomeClass 可以是 Spring 托管 bean(并用 @Component 注释),我可以按照你建议的方式设置 nameattempts 属性?
  • 为了使自动装配字段工作,SomeClass 应该是一个弹簧组件:@Component("someclass") public class SomeClass { ..........context.getBean(" someclass",name,attempts);
猜你喜欢
  • 2015-01-22
  • 1970-01-01
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多