1

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)
    }
}
user2401147
  • 11
  • 1
  • 2

1 Answers1

0

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?

Fausto
  • 183
  • 12
  • Can we have autowired A in class B and autowired B in class A, the thing is I have simplified the code just for explaining, the code what I am working with is more complicated. Also let me know the different wasy of creating bean using Spring – user2401147 Aug 14 '18 at 13:14
  • that would create a circular dependency flow and it is wrong. the code is yes simplified but also incorrect, if you post a piece of code that doesn't work we encourage you to post the code you actually have sowe can focus on your real problem and help you solve it. Spring uses many type of dependency injection mechanism: Annotations, XML or Java Based. Now it can be autowired or not. if you use one of this approach you should first understand it clearly, than you can think of mixing them together to get the most from them. I recommend you a book: Learning Spring, Packt. give it a try – Fausto Aug 14 '18 at 13:22