4

When I add the @Component annotation to a class, it creates two beans of the same type (class type) and I get an error that there is no unique bean identifier.

But when I remove the @Component annotation, I only get one bean.

I don't see where the other bean is created.

Here is the class where I add @Component to:

package main.serviceconfiguration;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
/* prefix of key in application.properties*/
@ConfigurationProperties("")
public class ServiceConfiguration {

    /* declare key suffixes here */

    /* Then add getters and setters for the keys' values */
}

Where I @Autowire the bean:

@Controller
@Service
@Configuration
@RequestMapping("/users")
@EnableConfigurationProperties(ServiceConfiguration.class)
public class UserRestController {

    @Autowired
    private UserRepository repo;

    @Autowired
    private ServiceConfiguration config;
    ...
}

However, in the package explorer of my Eclipse IDE, I see that under Spring Elements -> Beans -> @Component annotation, that there are two beans of type main.serviceconfiguration.ServiceConfiguration

one is called serviceConfiguration and the other is called main.serviconfiguration.ServiceConfiguration

The error from log:

No qualifying bean of type [main.serviceconfiguration.ServiceConfiguration] is defined: expected single matching bean but found 2: serviceConfiguration,main.serviceconfiguration.ServiceConfiguration
Kingamere
  • 9,496
  • 23
  • 71
  • 110

2 Answers2

4

That is curious.

What you can do is force a name for the component like @Component("foo") and then along with @Autowired add @Qualifier("foo")

This does not address the root cause though.

codesalsa
  • 882
  • 5
  • 18
3

@EnableConfigurationProperties(ServiceConfiguration.class) already creates a bean of that type. Generally, you have duplicated annotations on all your classes shown here, which aren't necessary. For instance, why have you @Controller and @Service on your class? One is enough. And if it is a controller, it shouldn't be a configuration class, so you should remove the annotation @Configuration.

dunni
  • 43,386
  • 10
  • 104
  • 99