SamPinheiro
SamPinheiro

Reputation: 143

Error with using @ComponentScan on multiple packages in Spring Boot

Here's my issue--I have a service that relies on an external library. I was trying to autowire the service so I can use it but was not able to

import org.keycloak.admin.client.token.TokenService;

public class SimpleService {

   @Autowired
   private TokenService keycloakTokenSvc; // Could not autowire, no beans of type 'TokenService' found
 
   public void execute() {
       keyCloakTokenSvc.doSomething();
   }
   

}

I then added this to my SpringBootApplication and got it working:

@SpringBootApplication
@ComponentScan({"org.keycloak.admin.client.token"})
public MyApp {}

Sweet -- all good now, right? Nope. It seems like this overrides some of my auto configuraitons like my security config, so I was no longer to make RESTful requests to my application while it was running. I then did this next:

@SpringBootApplication
@ComponentScan({"org.keycloak.admin.client.token", "com.project.pkg"})
public MyApp {}

Still nothing. I get the same error as before:

Field keycloakTokenSvc in com.mark43.jms.services.TokenRefreshService required a bean of type 'org.keycloak.admin.client.token.TokenService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'org.keycloak.admin.client.token.TokenService' in your configuration.

I'm new to Spring Boot so not sure what to do here. Is there a way to use the TokenService without Autowiring? Is there a way to scan both packages?

Upvotes: 0

Views: 449

Answers (1)

João Dias
João Dias

Reputation: 17460

It seems to me that you need to create a TokenService bean as follows:

@Configuration
public class TokenConfig {
    @Bean
    public TokenService tokenService() {
        return new TokenService();  // Or whatever you need to instantiate it
    }
}

This will register a TokenService object as a Spring-managed bean so that it can be autowired into SimpleService.

Upvotes: 1

Related Questions