Benefit of dependency injection for dynamically created objects

In the context of an IoC container such as Spring, I am looking for a way to inject some dependencies/properties into a class' instantiation. Not all properties of the object can be set using dependency injection, and the object is created dynamically in response to an application event. If all dependencies can be injected via the container, then a Spring managed bean would be ideal.

For instance, the class defined below must be annotated as a @Component (or more specialized annotation) for component scanning and dependency injection to work. But it has a couple of properties ( name and attempts ) that can only set be dynamically, by the application code and not the container. But if I have to use an endpoint and a restTemplate (which are already managed by the IoC container), providing them to this object via constructor or setter methods is not convenient.

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
}

Since there are some dynamically set properties, I cannot use the new keyword to instantiate the class and still reap the benefits of DI and IoC. Or can I?


You could use a factory. Something like the following:

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);

If I don't misunderstood you, you need to set the values in the constructor.

You can do it creating the bean from the context and setting the values:

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

链接地址: http://www.djcxy.com/p/14396.html

上一篇: 什么是依赖注入?

下一篇: 动态创建对象的依赖注入的好处