Composite design pattern with Spring annotations

Nick G. :

Fellow developers, I wonder what's the best approach to implement composite pattern with annotations in Spring. I am trying to create a component that wraps a collection of other components, and invokes corresponding methods on each:

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

This way if one repo fails, there is always a fallback. Implementing this with XML configs was easy just provide a list to the composite repo. With annotations, one way I can think of is to provide a custom configuration class. Is this the way to go?

Steve :

You can just inject a list of CourseRepository objects, and Spring will give you a list with all of the Beans it knows about of type CourseRepository. So simply:

@Autowired
private List<CourseRepository> repos;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96076&siteId=1