gpt4 book ai didi

Java - 重写在构造函数中创建的对象?

转载 作者:行者123 更新时间:2023-11-30 05:22:06 26 4
gpt4 key购买 nike

在下面的 Spring 服务中,我在 MyService 的构造函数中创建 ClassToCreate

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

}


}

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

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

最佳答案

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

@Component

公共(public)类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);
}

}

关于Java - 重写在构造函数中创建的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59372414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com