2
我有一個Spring Boot應用程序。我用@Component註解標註了一個項目的類。現在在我的主類中,當我試圖獲取類的bean時,我得到一個無法找到該bean的異常。org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有名爲'eventpublisher'的bean可用
Exception in thread "main" [2m2017-05-08 09:53:55.303[0;39m [32m INFO[0;39m [35m9112[0;39m [2m---[0;39m [2m[ Thread-2][0;39m [36ms.c.a.AnnotationConfigApplicationContext[0;39m [2m:[0;39m Closing org.spring[email protected]4df828d7: startup date [Mon May 08 09:53:54 EDT 2017]; root of context hierarchy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'eventpublisher' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at com.fannie.SpringEventGenerationJBsApplication.main(SpringEventGenerationJBsApplication.java:17)
我的類被註釋爲組分以下
@Component
public class EventPublisher implements ApplicationEventPublisherAware {
@Autowired
private ApplicationEventPublisher publisher;
public void eventpublishers() {
ActualEvent actualEvent = new ActualEvent(this);
System.out.println(actualEvent);
publisher.publishEvent(actualEvent);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
}
@SpringBootApplication
@ComponentScan(basePackages = {"com.fannie"})
public class SpringEventGenerationJBsApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringEventGenerationJBsApplication.class, args);
EventPublisher ep = (EventPublisher) context.getBean("eventpublisher");
ep.eventpublishers();
}
Bean名稱是從小寫的第一個字符的類名生成的......所以'EventPublisher'將成爲'eventPublisher'而不是'eventpublisher'。 –
謝謝你的作品。非常感謝。 – DP3
@ M.Deinum也許你應該添加這個答案。你剛剛解決了我的問題,如果我能,至少,upvote你會很棒。 –