我是Spring框架中的新手。 我尝试在@Component中使用@Bean注释配置2个bean。 之后,我尝试getBean(按名称),我得到了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:没有 豆 命名为&#39; tb1&#39;被定义为 在org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:577) 在org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111) 在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276) 在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) 在org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127) 在com.example.proxy.ComponentBeanTest.test(ComponentBeanTest.java:38)
答案 0 :(得分:2)
将@Component
替换为@Configuration
,这表示一个类声明了一个或多个@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());
}
}