简体   繁体   English

使用BeanFactory.getBean()创建Spring bean

[英]Creating spring bean using BeanFactory.getBean()

Consider there are 2 classes: When creating bean A using factory.getbean(), the bean gets created but the property coldata is null inspite of initializing to new hashmap. 考虑有两个类:使用factory.getbean()创建bean A时,将创建bean,但是属性初始化时为null,尽管初始化为新的hashmap。

@Component
@Scope("prototype")
public class A{
    private Map<String, Map<String,String>>  coldata = new  HashMap<String, Map<String,String>>();
}

@Service
public class B{
    @Autowired
    private BeanFactory factory;

    public void test(){
         A a= (A)factory.getBean("A");
         System.out.println(a.coldata)
    }
}

There's a wrong approach at first to correct. 首先有一个错误的方法来纠正。

First of all, as @Sun says: correct the code and make that map as public or give that field a getter at least. 首先,如@Sun所说:更正代码并使该地图公开,或至少使该字段具有吸气剂。

Secondly If you use autowiring don't use beanFactory: Class A is annotated as Autowired and as a Component. 其次,如果您使用自动装配,请不要使用beanFactory:类A被标注为自动装配和组件。 If you want an instance of that class from the container just use an autowired instance in class B: 如果要从容器中获取该类的实例,只需在B类中使用自动装配的实例:

@Service
public class B{
    @Autowired
    private A a;

    public void test(){
        System.out.println(a.coldata)
    }
}

avoid using the getBean method of the BeanFactory/ApplicationContext classes, especially if you want to use autowiring. 避免使用BeanFactory / ApplicationContext类的getBean方法,特别是如果要使用自动装配。 Here's a good explanation on why you should avoid using that method: Why is Spring's ApplicationContext.getBean considered bad? 这里有一个很好的解释,说明了为什么应该避免使用该方法: 为什么Spring的ApplicationContext.getBean被认为是错误的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过 BeanFactory.getBean(Class<T> ) - Retrieve a generic bean via BeanFactory.getBean(Class<T>) 如何在测试类字段中使用 BeanFactory.getBean()? - How can I use BeanFactory.getBean() in a test class field? 使用 getBean 在 Spring 中获取 bean - Fetching a bean in Spring using getBean 通过 Spring BeanFactory::getBean() 传递 A.class - Pass A.class through Spring BeanFactory::getBean() 在 spring 中使用 applicationContext.getBean() 创建 bean 时如何指定要使用的组件? - How do I specify which component to use while creating the bean using applicationContext.getBean() in spring? 在Spring中无需使用ApplicationContext.getBean()即可动态自动装配bean - Dynamically autowire a bean without using ApplicationContext.getBean() in Spring 使用 spring boot 在 TestNg 测试用例中提供 BeanFactory Bean - Provide BeanFactory Bean in TestNg test cases using spring boot AnnotationConfigApplicationContext.getBean 返回一个不同的 bean,Spring - AnnotationConfigApplicationContext.getBean returns a different bean, Spring 为什么将BeanFactory注入Spring组件却不注入Spring Bean是正常的呢? - Why it is normal to inject BeanFactory to Spring component but isn't to Spring Bean? 如何在Spring Boot中用自己的模拟替换BeanFactory中的bean? - How to replace bean in BeanFactory with own mock in Spring Boot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM