@Autowired来自子类的抽象类

时间:2018-03-10 01:52:23

标签: java spring subclass autowired

我有一个针对特定类型资源(症状)的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);
    }
    ...
}

但是,由于我需要生成更多控制器,对于其他资源,我想生成一个抽象类和子类

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;

    ...
}

但我不知道以某种方式将子类中的自动元素以一种很好的方式传递给抽象类是可能的(即不在每个函数调用中将它们作为参数发送)。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

将依赖项移至父级。

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");
    }    
}