spring FactoryBean is to create complex beans. Generally, beans can be configured directly with xml. If a bean is created, it is difficult to configure with xml. At this time, you can consider using FactoryBean.
Examples are as follows:
1: Creating a Car class (for simplicity) generally cannot directly give the Car class. If so, it can be directly injected or a Car object. This is just for simplicity.
package ; public class Car { private String make; private int year; public String getMake() { return make; } public void setMake(String make) { = make; } public int getYear() { return year; } public void setYear(int year) { = year; } }
2: A FactoryBean implementation has created a car
package ; import ; public class MyCarFactoryBean implements FactoryBean<Car>{ private String make; private int year; public void setMake(String make) { = make; } public void setYear(int year) { = year; } @Override public Car getObject() throws Exception { // TODO Auto-generated method stub //Here is a complex car object created // wouldn't be a very useful FactoryBean // if we could simply instantiate the object! Car car = new Car(); if(year != 0){ (); } if("make".equals(make)){ ("we are making bla bla bla"); }else{ (); } return car; } @Override public Class<?> getObjectType() { // TODO Auto-generated method stub return ; } @Override public boolean isSingleton() { // TODO Auto-generated method stub return false; } }
The above is too simple to create a car. If it is too simple, there is no need to create it with FactoryBean. It can be written more complicatedly.
3: Person quotes a car
package ; public class Person { private Car car; public Car getCar() { return car; } public void setCar(Car car) { = car; } public String toString(){ return ()+"::::"+(); } }
4: Configure the reference xml format:
<bean class=""> <property name="make" value="makeing car"/> <property name="year" value="123"/> </bean> <bean class=""> <property name="car" ref="car"/> </bean>
5: Write tests:
package ; import ; import ; public class MainTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("resource/"); Person person = (Person)("person"); // Car car = (Car)("car"); // (car); (person); } }
Test results making car::::123
Create a car successfully with FactoryBean
Just to illustrate the thought. Because this interface is too important. There are many classes in Spring that implement this interface.
The above is a detailed explanation of FactoryBean in Spring introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!