Say I have a class
class Service {
private final Repository repository
@Autowired
public Service(Repository repository) {
this.repository = repository
}
}
It autowires the repository class. Say I wanted to change it to also add something dynamically and I would like to do it through a static factory method while also maintaining my dependency. I would try to do something like this:
class Service {
private final Repository repository;
private String field;
@Autowired
public Service(Repository repository) {
this.repository = repository
}
private Service() {}
public static Service of(String field) {
Service service = new Service();
service.setField(field);
return service;
}
private void setField(String field) {
this.field = field;
}
}
But this code won't work because the repository
wont actually be instantiated.
Is there any way for me to be able to both inject a spring dependency and a dynamic attribute?
Thank you!