0

我无法使用 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
4

1 回答 1

4

我敢打赌你已经MessageServiceImpl@Service或类似的注释。结合类路径扫描,这意味着正在创建两个 MessageServiceImpl bean,一个由扫描创建,一个由messageService方法创建。摆脱其中一个。

于 2013-04-26T16:12:36.480 回答