简体   繁体   English

春季启动:@Autowired不适用于以下课程之一

[英]Spring Boot: @Autowired is not working for one of the class

I am developing OAuth implementation with Jwt tokens. 我正在使用Jwt令牌开发OAuth实现。 It's kind of weird but for class TokenAuthenticationService When I try to Autowired this class in a different package, I get Consider defining a bean of type 'com.company.security.TokenAuthenticationService' in your configuration. 这是一种奇怪,但对类TokenAuthenticationService当我尝试Autowired在不同的包这个班,我得到Consider defining a bean of type 'com.company.security.TokenAuthenticationService' in your configuration. I did a workaround and added @Bean TokenAuthenticationService in that class. 我做了一个变通办法,并在该类中添加了@Bean TokenAuthenticationService
Now when I am trying to initialize an interface in the TokenAuthenticationService class, it gives the same type of error for that interface. 现在,当我尝试在TokenAuthenticationService类中初始化接口时,它为该接口提供了相同类型的错误。 Consider defining a bean of type 'com.company.security.UserService' in your configuration.

ComponentScan annotation is configured like @ComponentScan({"com.company"}) ComponentScan批注的配置方式类似于@ComponentScan({"com.company"})

What I am missing here and why? 我在这里缺少什么,为什么?

You have two ways to define beans for autowiring in your project. 您有两种方法来定义要在项目中自动装配的bean。

With classes defined by you , you can use the @Component annotation (or, for service classes, @Service annotation) this way: 对于您定义的类 ,可以通过以下方式使用@Component批注(对于服务类,可以使用@Service批注):

@Service
public class TokenAuthenticationService { ... }

If you are using third party classes , you can configure them in a configuration class: 如果使用第三方类 ,则可以在配置类中对其进行配置:

@Configuration
public MyProjectConfig {
    @Bean
    public ThirdPartyClass serviceClass() { new ThirdPartyClass(); }
}

(Using @Bean annotation is not a workround. You just need to understand its purpose...) (使用@Bean注释不是一种解决方法。您只需要了解它的用途...)

This way autowiring should work... 这种自动接线应该可以工作...

Pay attention to difference between @Component and @Bean annotations . 注意@Component和@Bean批注之间的区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM