首页 > 解决方案 > Java - 覆盖在构造函数中创建的对象?

问题描述

在以下 Spring 服务中,我ClassToCreateMyService.

 @Service("MyService")
 public class MyService {

  private final Repository repository;
  private final ClassToCreate classToCreate;

        @Autowired
        public MyService(
                Repository repository,
                @Value("${path}") String path
                ) {

            this.ClassToCreate = new ClassToCreate(repository, path);
        }

        public void myMethod(Object object){

        String appendedPath = path + object.id();

        //create different instance of classToCreate with variable appended
        ClassToCreate classToCreate = new ClassToCreate(repository, appendedPath);

        classToCreate.doSomething();

        }


    }

创建和使用ClassToCreate我正在尝试的不同实例myMethod而不是使用构造函数中的内容的最佳方法是什么?

我想在这里使用构造函数的路径创建该类的不同实例,但附加 object.id 作为ClassToCreate. 我还需要使用与repository传递给MyService构造函数的值相同的值。

标签: javaspringconstructoroverridingautowired

解决方案


您可以使用组合。您可以使用组件(Spring 中的 @Component)。创建返回 ClassToCreate 对象的工厂方法。

@Component

公共类 ClassToCreateFactory {

private Repository repository;
private String path;

@Autowired
public ClassToCreateFactory (Repository repository, @Value("${path}") String path) {
    this.repository = repository;
    this.path = path;
}    

public static ClassToCreate getClassToCreate() {
    return new ClassToCreate(repository, path);
}

}


推荐阅读