[英]Can't create service using Spring and JavaConfig
我無法使用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
我敢打賭,您已經用@Service
或類似的注釋了MessageServiceImpl
。 與類路徑掃描結合使用,這意味着將創建兩個MessageServiceImpl Bean,一次是通過掃描,一次是從messageService
方法。 擺脫一個或另一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.