In the following Spring service I am creating ClassToCreate
in the constructor of MyService
.
@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();
}
}
What is the best way to create and use a different instance of ClassToCreate
as I am attmempting in myMethod
rather than use what is in the constuctor?
I want to create a different instance of the class here using the path from constructor but with the object.id appended as the path for ClassToCreate
. I also need to use the same repository
value as is passed into the MyService
constructor.
You can use composition. You can use a component (@Component in Spring). Create factory method which returns objects of ClassToCreate.
@Component
public class 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.