Issue
my tested code
package com.annotations.annotations;
import org.springframework.stereotype.Component;
@Component("college") public class College {
public void id() {
System.out.println("33");
}
@Configuration public class Config {
@Bean
public College name() {
return new College();
}
}
import javax.naming.Context;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext mech=new AnnotationConfigApplicationContext(Config.class);
College lokesh=mech.getBean("college",College.class);
lokesh.id();
}
I am getting error like this
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'college' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:872) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160) at com.annotations.annotations.App.main(App.java:15)
Solution
You must specify the bean name
@Bean(name = "college")
public College name() {
return new College();
}
Answered By - HaiZi
Answer Checked By - Mary Flores (JavaFixing Volunteer)