Himanshu Yadav
Himanshu Yadav

Reputation: 13585

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

I am developing OAuth implementation with Jwt tokens. 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. I did a workaround and added @Bean TokenAuthenticationService in that class.
Now when I am trying to initialize an interface in the TokenAuthenticationService class, it gives the same type of error for that interface. Consider defining a bean of type 'com.company.security.UserService' in your configuration.

ComponentScan annotation is configured like @ComponentScan({"com.company"})

What I am missing here and why?

Upvotes: 0

Views: 5354

Answers (1)

davioooh
davioooh

Reputation: 24706

You have two ways to define beans for autowiring in your project.

With classes defined by you, you can use the @Component annotation (or, for service classes, @Service annotation) this way:

@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...)

This way autowiring should work...

Pay attention to difference between @Component and @Bean annotations.

Upvotes: 2

Related Questions