Sam Jones
Sam Jones

Reputation: 1548

Deciding which implementation to inject

I have a Spring project, split into several modules.

  1. data access library (spring-data-jpa; entities and repositories)
  2. security library (spring-security; including an extended repository with @PreAuthorize annotations)
  3. web project (depends on both libraries)
  4. batch project (depends only on data, since there's no user to authenticate in Spring)

So in the data access library, I have this interface:

@Repository
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
    List<Item> findAll();
    Item findById(Long id);
}

And in the security library:

@Repository
public interface SecuredItemRepository extends ItemRepository {

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    List<Item> findAll();

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    Item findById(Long id);
}

When I @Autowire an ItemRepository, I would like it to use SecuredItemRepository if it's available, and ItemRepository if not.

Is there a way to declare the SecuredItemRepository as the default choice, or first in the list of ItemRepository implementations to grab? I'd rather not specify the implementation in every location that I need to access the database.

Upvotes: 0

Views: 37

Answers (1)

Sam Jones
Sam Jones

Reputation: 1548

And of course, two seconds later I find the answer. I needed to annotate SecuredItemRepository with this:

@Priority(value = Ordered.HIGHEST_PRECEDENCE)

Upvotes: 1

Related Questions