无法使用Spring和JavaConfig创建服务

时间:2013-04-26 15:57:25

标签: java spring

我无法使用Spring和JavaConfig创建服务。

这是我的主要课程:

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());
    }
}

这是我的配置

@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;
    }


}

这是错误:

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

1 个答案:

答案 0 :(得分:4)

我敢打赌你用MessageServiceImpl或类似的方式注释了@Service。结合类路径扫描,这意味着正在创建两个MessageServiceImpl bean,一次通过扫描,一次来自messageService方法。摆脱其中一个。