[英]@Autowired abstract class from subclass
I have a controller for REST services for a particular type of resources (Symptoms) that looks like this: 我有一个用于REST服务的控制器,用于特定类型的资源(症状),如下所示:
@RequestMapping(value = "/symptom", produces = "application/json")
public class SymtomController {
@Autowired
private SymptomRepository repository;
@Autowired
private SymptomResourceAssembler assembler;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<SymptomResource>> findAllSymptoms() {
List<SymptomEntity> symptoms = repository.findAll();
return new ResponseEntity<>(assembler.toResourceCollection(symptoms), HttpStatus.OK);
}
...
}
But, as I need to produce more controllers, for other resources, I would like to generate an abstract class and subclasses 但是,由于我需要产生更多的控制器,因此对于其他资源,我想生成一个抽象类和子类。
public class AbstractController<Entity extends AbstractEntity, Resource extends GenericResource {
// repository and assembler somehow transferred from subclasses
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<Resource>> findAllResources() {
List<Entity> entities = repository.findAll();
return new ResponseEntity<>(assembler.toResourceCollection(entities), HttpStatus.OK);
}
...
}
@RequestMapping(value = "/symptom", produces = "application/json")
public class SymtomController extends ResourceController<SymptomEntity, SymptomResource>{
@Autowired
private SymptomRepository repository;
@Autowired
private SymptomResourceAssembler assembler;
...
}
But I do not know it is possible, somehow, to transfer the autowired elements in the subclasses to the abstract class in a nice way (ie not sending them as parameters on each function call). 但是我不知道有可能以某种不错的方式将子类中的自动装配的元素转移到抽象类中(即,在每次函数调用时都不将其作为参数发送)。
Any ideas? 有任何想法吗?
Move the dependencies to the parent. 将依赖项移至父项。
abstract class Parent {
@Autowired
protected MyRepository repo;
@PostConstruct
public void initialize(){
System.out.println("Parent init");
Assert.notNull(repo, "repo must not be null");
}
}
@Component
class Child extends Parent {
@PostConstruct
public void init(){
System.out.println("Child init");
Assert.notNull(repo, "repo must not be null");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.