【问题标题】:In springboot autowired is not working, always null?在 springboot 中,autowired 不起作用,总是为空?
【发布时间】:2018-03-01 06:14:20
【问题描述】:

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

@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 进行基础包发现

【问题讨论】:

  • CustomUserService 实现类是否使用了注解
  • @Service@Component放在实现CustomUserService接口的类上,也别忘了把这个实现类放在组件扫描的雷达上。
  • 向你展示stacktrace,完整类CustomAuthenticationProvider和主类
  • 删除了一些行:java.lang.NullPointerException: null at com.example.demo.configs.CustomAuthenticationProvider.authenticate(CustomAuthenticationProvider.java:74) ~[classes/:na] at org.springframework。 security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager .java:199) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE] 在

标签: spring spring-mvc spring-boot spring-security autowired


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    检查是否注释了CustomUserService implementation@Component@Service,以及组件扫描是否可以发现该服务。

    【讨论】:

    • 为基础包发现保留服务注释和 ComponentScan 注释
    • 我对提供的代码 @override someMethod(){//method of CustomUserService interface. userService.display();//here "userService" is always null coming } 感到困惑。对于方法someMethod(),您评论为//method of CustomUserService interface。但是您使用了 @override 。仍然是 CustomAuthenticationProvider 类仅实现 AuthenticationProvider
    • 我正在使用 javainsimpleway.com/… 中的代码。在 CustomAuthenticationProvider 类中,“userService”引用始终为空
    • 如果你用new 实例化一个对象CustomUserService 也会发生这种情况
    【解决方案3】:

    在 Spring Boot 应用程序中,您不必显式启用组件扫描。所有带注释的类将自动注册为存在于 spring-boot 应用程序类(使用@SpringBootApplication 注释)的包下的 bean。

    因此,如果您的 Application 类存在于 com.abc 包中,则将扫描 com.abc 的所有子包以查找 Spring bean。参考下面的树:

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

    在您的情况下,可能无法发现 bean,因为它们位于应用程序类包之外。

    【讨论】:

      【解决方案4】:

      我的错!.......在代码中的某些地方我使用 new 关键字创建 CustomAuthenticationProvider 的实例,这就是为什么 spring 不在 CustomAuthenticationProvider 类中自动装配实例的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多