簡體   English   中英

復合設計模式與春天注釋

[英]Composite design pattern with Spring annotations

對於開發人員,我想知道在Spring中使用注釋實現復合模式的最佳方法是什么。 我正在嘗試創建一個包裝其他組件集合的組件,並在每個組件上調用相應的方法:

@Slf4j
@Repository("courseRepository")
public class CompositeRepository implements CourseRepository {

    private List<CourseRepository> repos = new ArrayList<CourseRepository>();

    @Override
    public Page<Subject> findSubjects(AcademicCareer career, Pageable pageable) {
        for (CourseRepository r : repos) {
            try {
                return r.findSubjects(career, pageable);
            } catch (Exception e) {
                log.info("Unable to invoke findSubjects on " + r, e);
            }
        }
        throw new IllegalStateException("Unable to complete findSubjects");
    }
}

這樣,如果一個回購失敗,總會出現回退。 使用XML配置實現這一點很簡單,只需為復合倉庫提供一個列表即可。 使用注釋,我能想到的一種方法是提供自定義配置類。 這是要走的路嗎?

您只需注入一個CourseRepository對象列表,Spring將為您提供一個列表,其中包含它所知道的所有類型為CourseRepository的Bean。 簡單地說:

@Autowired
private List<CourseRepository> repos;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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