【问题标题】:Spring: Cannot get bean by using @Component and @BeanSpring:无法使用@Component 和@Bean 获取bean
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的支持。它工作正常。如果我保留 Component 注释,它将与 Autowired 一起正常工作,但不能使用 context.getBean("tb1")。我不明白这个机制。
    • 使用组件时,该类是自动装配的有效候选者,因为标有 Bean 的方法被视为普通方法声明,不会生成 bean。但是在使用Configuration的时候,标有Bean的方法被当成生成spring bean,生成bean。
    • 谢谢。我想了解有关此问题的更多详细信息。你能给我研究的文件或钥匙吗?
    • 查看 spring 官方参考和 API 文档以获取更多信息。
    • 很好。非常感谢。
    猜你喜欢
    • 2016-10-31
    • 2018-06-13
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多