How to use @Autowired in not Spring's stereotype classes

我怕爱的太早我们不能终老 提交于 2020-01-24 19:29:05

问题


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);
     }
}

回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/55195769/how-to-use-autowired-in-not-springs-stereotype-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!