簡體   English   中英

子類的@Autowired抽象類

[英]@Autowired abstract class from subclass

我有一個用於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;

    ...
}

但是我不知道有可能以某種不錯的方式將子類中的自動裝配的元素轉移到抽象類中(即,在每次函數調用時都不將其作為參數發送)。

有任何想法嗎?

將依賴項移至父項。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM