2

I would like to use that repository in this class, but when I put a stereotype like @Component, I get an error from the IDE:

Could not autowire. No beans of 'Authentication' type found.

public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    @Autowired
    private FlatRepository flatRepository;

    public CustomMethodSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
     }
}
Bence Szabari
  • 143
  • 1
  • 2
  • 12
  • Where *is* that constructor-injected value going to come from? – jonrsharpe Mar 16 '19 at 10:36
  • You ask how to inject something into a non-managed class, but your class obviously needs to be managed as it's trying to configure Spring Security. So the question doesn't make sense. You're getting the error because the only constructor requires `Authentication`. – kaqqao Mar 16 '19 at 10:41
  • Okay, I got that, but still don't know how should I use the repository within this class? – Bence Szabari Mar 16 '19 at 10:45

2 Answers2

4

You cannot @Autowire inside a SecurityExpressionRoot.
You can however manually provide that FlatRepository dependency.

As you're configuring your Security objects inside a @Configuration class, there you're able to @Autowire any instance you need.

Simply make space for that new dependency in CustomMethodSecurityExpressionRoot constructor

class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot 
                                         implements MethodSecurityExpressionOperations {
    private final FlatRepository flatRepository;

    CustomMethodSecurityExpressionRoot(
            final Authentication authentication,
            final FlatRepository flatRepository) {
        super(authentication);
        this.flatRepository = flatRepository;
    }

    ...
}

And manually inject it at instantiation point

final SecurityExpressionRoot root = new CustomMethodSecurityExpressionRoot(authentication, flatRepository);
LppEdd
  • 20,274
  • 11
  • 84
  • 139
0

To use an Autowired instance of a bean, you need the component/service using that instance to also be managed by Spring. So in order to use the repository, you need to springify the CustomMethodSecurityExpressionRoot class. Either you annotate the class with an @Component / @Service annotation and pick it up with a component scan or configure the bean using Java or XML configuration.

If you "Springify" the CustomMethodSecurityExpressionRoot, then you need to make sure that the Authentication object is obtainable by the spring Application context. That is why you get the error that Authentication cannot be found. You will need to create a bean of type Authentication in Java or XML as well.

Please check the official documentation for how to define a spring bean:

https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

Nullbeans
  • 309
  • 1
  • 8