DP3
DP3

Reputation: 128

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'eventpublisher' available

I have a Spring Boot application. I annotated a class of the project with @Component annotation. Now in my main class, when I am trying to get a bean of the class, I get an exception that it was not able to find the 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)

My class that is annotated as component is following

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

Upvotes: 2

Views: 2723

Answers (1)

M. Deinum
M. Deinum

Reputation: 125212

As documented here

Spring generates bean names for unnamed components, following the rules above: essentially, taking the simple class name and turning its initial character to lower-case

So when having a class EventPublisher which is detected by component-scanning the resulting bean name will be eventPublisher.

Upvotes: 0

Related Questions