BinhLe
BinhLe

Reputation: 13

Spring: Cannot get bean by using @Component and @Bean

I'm new in Spring framework. I try to config 2 beans with @Bean annotation within @Component. After that, I try to getBean (by name), I got a NoSuchBeanDefinitionException. Please help me to resolve it.

Here is my code: - The component:

package com.example.component;

@Component
public class FactoryMethodComponent {

 private static int i;

 @Bean
 @Qualifier("public")
 public TestBean publicInstance() {
    return new TestBean("publicInstance");
 }

 @Bean
 @Qualifier("tb1")
 public TestBean1 publicInstanceTB1() {
    return new TestBean1(publicInstance());
 }
}

-The xml configuration file: app-context.xml.

<beans ...>
    <context:component-scan base-package="com.example.*" />
</beans>

-The test code:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:app-context.xml" })
public class ComponentBeanTest {
@Test
public void test() {
    System.out.println(((TestBean1)context.getBean("tb1")).getTestBean().getMethodName());
    System.out.println(publicTestBean.getMethodName()); 
}
}

-Exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'tb1' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:577) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127) at com.example.proxy.ComponentBeanTest.test(ComponentBeanTest.java:38)

Upvotes: 1

Views: 2598

Answers (1)

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

Replace @Component with @Configuration which indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@Configuration
public class FactoryMethodComponent {

 private static int i;

 @Bean
 @Qualifier("public")
 public TestBean publicInstance() {
    return new TestBean("publicInstance");
 }

 @Bean
 @Qualifier("tb1")
 public TestBean1 publicInstanceTB1() {
    return new TestBean1(publicInstance());
 }
}

Upvotes: 2

Related Questions