Tuesday, January 7, 2014

Spring Course: V12 Factory Beans and Method

in this video we will initiate the bean by using a factory method.

to do that, you should define a factory method in the class. 

as you can see we defined getInstance as a factoryMethod which returns a person object, sure the factory method must be static.

now in the beans.xml.

in order to use the factory method you use factory-method="getInstance", and the parameters that you want to pass to getInstance (in this case the id and the name) should be defined as <constructor-arg>

Factory Bean
in addition you can define a Factory class, we will define a PersonFactory class, 

and now in order to use this class to create a bean, you write

as you can see you should
1- define a PersonFactory bean
2- use factory-method and factory-bean attributes, in the Person bean.

Note: lets say that you have multiple beans in beans.xml, all singleton beans will be initiated when you run:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

and not when you run (Person)context.getBean("person");

No comments:

Post a Comment