Repository injection in an handler spring boot class performance

24 Views Asked by At

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);
  1. It' this injection performant?
  2. There is a best way to do that?
  3. There is a way to inject directly in the PermissionEvaluator class?

Thanks

0

There are 0 best solutions below