【发布时间】:2018-04-03 06:32:24
【问题描述】:
我是 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: 否 豆角,扁豆 名为“tb1”的定义 在 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)
【问题讨论】:
标签: spring annotations components javabeans