Spring: 无法使用@Component 和@Bean 获取bean

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

我是 Spring 框架的新手。 我尝试在@Component 中使用@Bean 注释配置2 个bean。 之后,我尝试获取 Bean(按名称),我得到了一个 NoSuchBeanDefinitionException。 请帮我解决一下。

这是我的代码: - 组件:

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

-xml配置文件:app-context.xml.

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

-测试代码:

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

-异常:

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)

@Component替换为@Configuration,这表明class声明了一个或多个@Bean方法,并且可以由Spring容器处理以生成bean定义和在运行时对这些 bean 的服务请求。

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