当前位置: 首页 > 知识库问答 >
问题:

组织。springframework。豆。工厂NoSuchBeanDefinitionException:没有名为“eventpublisher”的bean可用

松献
2023-03-14

我有一个Spring启动应用程序。我用@Component注释了项目的一个类。现在在我的主类中,当我试图获取该类的bean时,我得到一个异常,它无法找到该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.springframework.context.annotation.AnnotationConfigApplicationContext@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();
    }

共有1个答案

聂奇
2023-03-14

如本文所述

Spring按照上面的规则为未命名的组件生成bean名称:本质上,取简单的类名,并将其初始字符转换为小写

因此,当具有通过组件扫描检测到的类EventPublisher时,生成的bean名称将是eventPublisher

 类似资料: