I'm wondering about the best approach to inject the repository class into one of my utility classes, or rather a handler, to query the database. I approached it with this style:by injecting the repository into the configuration and then passing it to the component class. But is it the best way?
Configuration class:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AuthorizationConfiguration extends GlobalMethodSecurityConfiguration {
@Autowired
private UserRepository userRepository;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler =
new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new PermissionEvaluator(userRepository));
return expressionHandler;
}
}
So in the component I use the UserRepository Injected:
@Component
public class PermissionEvaluator implements PermissionEvaluator {
private UserRepository UserRepository;
public PermissionEvaluator(UserRepository userRepository) {
this.UserRepository = UserRepository;
}
// methods with the repo for interact with database
private boolean hasPrivilege(Authentication auth, String permission) {
String username = auth.getName();
User user = userRepository.findByUsername(username);
- It' this injection performant?
- There is a best way to do that?
- There is a way to inject directly in the PermissionEvaluator class?
Thanks