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);
}
}
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.