Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - @Component Annotation creates two beans of same type

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
like image 346
Kingamere Avatar asked Sep 02 '25 05:09

Kingamere


1 Answers

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.

like image 66
codesalsa Avatar answered Sep 04 '25 23:09

codesalsa