Parse the getObject () method instance in FactoryBean in spring,
This article focuses on the getObject () method in FactoryBean in spring. The details are as follows.
The FactoryBean interface defines the following three interface methods:
- Object getObject (): returns the Bean instance created by FactoryBean. If isSingleton () returns true, the instance is placed in the cache pool of a single instance of the Spring container.
- Boolean isSingleton (): determines whether the scope of the Bean created by FactoryBean is singleton or prototype.
- Class getObjectType (): return the type of the Bean created by FactoryBean.
When the implementation class of the <bean> class attribute configuration in the configuration file is FactoryBean, The getBean method returns not the FactoryBean itself, but the object returned by the FactoryBean # getObject () method, this is equivalent to FactoryBean # getObject () proxy's getBean () method.
When we configure a Car, each attribute of the Car corresponds to a <property> element tag. If we suspect that this method is not concise, and we want to use commas to separate the configuration values for all the attributes of the Car at a time, we can write a FactroyBean to achieve our goal:
import org.springframework.beans.factory.FactoryBean;public class CarFactoryBean implements FactoryBean{private String carInfo;public Stirng getCarInfo(){return carInfo;}public void setCarInfo(String carInfo){this.carInfo=carInfo;}public Object getObject()throws Exception{Car car=new Car();String[]infos = carInfo.split(",");car.setBrand(infos[0]);car.setMaxSpeed(Integer.aarseint(infos[1]));car.setPrice(double.parsedouble(infos[2]));return car;}public Class getObjectType(){return Car.class;}public Boolean isSingleton() {return true;}}
With this CarFactoryBean, we can use the following configuration method to define the Car Bean in the configuration file:
<Bean id = "car" class = "com. lxm. fb. carFactoryBean "> <property name =" carInfo "value =" Hongqi CA72, 200,200 00.00 "/> </bean>
When getBean ("car") is called, Spring uses the reflection mechanism to find that CarFactoryBean implements the FactoryBean interface. Then, the Sping container calls the interface method CarFactoryBean # getObject () returns the object created by the factory class. If you want to obtain the CarFactoryBean instance, You need to explicitly add the "&" Prefix: getBean ("& car") before beanName when using the getBean (beanName) method ").
Summary
The above is all the content about parsing the getObject () method instance in FactoryBean in spring. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!