Q:

Can't create service using Spring and JavaConfig

I Can't create service using Spring and JavaConfig.
Here is my main class:
public class MainApp
{

    private static final Logger LOGGER = getLogger(MainApp.class);

    public static void main(String[] args)
    {
        ApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        MessageService mService  = context.getBean(MessageService.class);

        HelloWorld helloWorld = context.getBean(HelloWorld.class);

        LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());

        Message message = new Message();
        message.setMessage(helloWorld.getMessage());
        mService.SaveMessage(message);

        helloWorld.setMessage("I am in Staten Island, New York");

        LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());
    }
}

Here is my config
@Configuration
@ComponentScan(basePackages = {"com.xxxx.HelloSpringJavaBasedJavaConfig"})
@Import(DatabaseConfig.class)
@PropertySource("classpath:application.properties")
public class HelloWorldConfig
{

    @Autowired
    Environment env;

    @Bean
    public MessageService messageService() {
        return new MessageServiceImpl();
    }

    @Bean
    public HelloWorld getHelloWorld()
    {
        HelloWorld hw = new HelloWorld();

       /*
        This is use to read in the property from the application.properties file
       */

        hw.setMessage(env.getProperty("bean.text"));

        return hw;
    }

}

here is the error:
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.xxxx.HelloSpringJavaBasedJavaConfig.service.MessageService] is defined: expected single matching bean but found 2: messageServiceImpl,messageService

A:

I bet you've annotated MessageServiceImpl with @Service or similar. Combined with classpath scanning, that means two MessageServiceImpl beans are being created, once by the scanning, and once from the messageService method. Get rid of one or the other.

