在 springboot 中,autowired 不起作用,始终为 null?

In springboot autowired is not working, always null?

在 spring-boot 应用程序中使用 springsecurity 编写自定义验证。 CustomUserService 是一个接口,有一个实现 class 和一个从数据库中获取数据的存储库。

@Component
    public class CustomAuthenticationProvider implements AuthenticationProvider{
    @Autowired
    private CustomUserService userService;

    @override
    someMethod(){//method of CustomUserService interface.
    userService.display();//here  "userService"  is always  null coming
    }
    }

在实现中保留@service 并使用@ComponentScan 进行基础包发现

只要该接口只有一个实现,并且该实现用@Component注解并启用Spring的组件扫描,那么Spring框架就可以找到(接口, 实现) 对。

在这种情况下,如果它是 null ,那么要么实现 class 没有用 @Component 注释,要么组件扫描不起作用

检查是否注解CustomUserService implementationclass@Component@Service,组件扫描是否能发现该服务。

在spring 引导应用程序中,您不必明确启用组件扫描。所有带注释的 classes 将自动注册为存在于 spring-boot 应用程序 class(带 @SpringBootApplication 注释)的包下的 beans。

因此,如果您的应用程序 class 存在于 com.abc 包中,则将扫描 com.abc 的所有子包以查找 spring bean。参考下面的树:

+--- src
|   +--- main
|   |   +--- java
|   |   |   +--- com
|   |   |   |   +--- application
|   |   |   |   |   +--- Application.java
|   |   |   |   |   +--- beans
|   |   |   |   |   |   +--- ASpringBean.java
|   |   |   |   |   |   +--- AnotherSpringBean.java

可能在你的情况下,bean 没有被发现,因为它们在应用程序 class 包之外。

我的错!..........在代码中的某些地方我使用了 new 关键字来创建 CustomAuthenticationProvider 的实例,所以这就是为什么 spring 没有在 CustomAuthenticationProvider class 中自动装配实例.