Spring 控制器中一项服务的不同实现取决于经过身份验证的用户的权限
Spring different implementations of one service in controller depended on authenticated user's authority
我的 spring 项目中有一个 ReservationController,它注入了 ReservationService。
Here is my ReservationController Class
我有两个 ReservationService 的实现:ReservationServiceImpl 和 ReservationDoublePriceServiceImpl。
Here is my ReservationService1 Class
Here is my ReservationService2 Class
我希望 ReservationController 根据经过身份验证的用户权限选择服务的实现(如果权限是 User 选择 ReservationServiceImpl 如果权限是 DoublePriceUser 选择 ReservationDoublePriceServiceImpl).
有人可以建议我该怎么做吗?
P.S 我已经完成了 application.properties 参数和限定符,但是 它只让我有机会只选择我的服务实现之一 。
如何在运行时选择服务bean?
有很多方法可以做到这一点,我建议从简单的开始。在您的 ReservationService
接口中添加一个 supports(Set<String> authorities)
方法,实现本身将判断它是否支持传递的权限(检查是否包含该角色)。
创建工厂 class,它将用于为您选择正确的实现,如下所示:
@Component
public class ReservationServiceFactory {
private final List<ReservationService> services;
public ReservationService getService(Set<String> authorities) {
for (ReservationService service : this.services) {
if (service.supports(authorities)) {
return service;
}
}
throw new IllegalArgumentException("Could not resolve ReservationService for authorities " + authorities);
}
}
public interface ReservationService {
// add this method in your ReservationService interface
boolean supports(Set<String> authorities);
}
并且,在您的控制器中,您可以执行以下操作:
@GetMapping
public void anyMethod(/*inject the authentication object*/Authentication authentication) {
this.reservationServiceFactory.getService(authentication.getAuthorities()).doSomething();
}
我的 spring 项目中有一个 ReservationController,它注入了 ReservationService。 Here is my ReservationController Class
我有两个 ReservationService 的实现:ReservationServiceImpl 和 ReservationDoublePriceServiceImpl。 Here is my ReservationService1 Class
Here is my ReservationService2 Class
我希望 ReservationController 根据经过身份验证的用户权限选择服务的实现(如果权限是 User 选择 ReservationServiceImpl 如果权限是 DoublePriceUser 选择 ReservationDoublePriceServiceImpl).
有人可以建议我该怎么做吗?
P.S 我已经完成了 application.properties 参数和限定符,但是 它只让我有机会只选择我的服务实现之一 。
如何在运行时选择服务bean?
有很多方法可以做到这一点,我建议从简单的开始。在您的 ReservationService
接口中添加一个 supports(Set<String> authorities)
方法,实现本身将判断它是否支持传递的权限(检查是否包含该角色)。
创建工厂 class,它将用于为您选择正确的实现,如下所示:
@Component
public class ReservationServiceFactory {
private final List<ReservationService> services;
public ReservationService getService(Set<String> authorities) {
for (ReservationService service : this.services) {
if (service.supports(authorities)) {
return service;
}
}
throw new IllegalArgumentException("Could not resolve ReservationService for authorities " + authorities);
}
}
public interface ReservationService {
// add this method in your ReservationService interface
boolean supports(Set<String> authorities);
}
并且,在您的控制器中,您可以执行以下操作:
@GetMapping
public void anyMethod(/*inject the authentication object*/Authentication authentication) {
this.reservationServiceFactory.getService(authentication.getAuthorities()).doSomething();
}