简体   繁体   中英

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.

@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.

Secondly If you use autowiring don't use beanFactory: Class A is annotated as Autowired and as a Component. If you want an instance of that class from the container just use an autowired instance in class 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. Here's a good explanation on why you should avoid using that method: Why is Spring's ApplicationContext.getBean considered bad?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM