Reputation: 597
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?
Upvotes: 4
Views: 1790
Reputation: 23139
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;
Upvotes: 3