详解Spring中的FactoryBean
程序员文章站
2024-03-01 21:29:22
spring factorybean 是创建 复杂的bean,一般的bean 直接用xml配置即可,如果一个bean的创建过程中涉及到很多其他的bean 和复杂...
spring factorybean 是创建 复杂的bean,一般的bean 直接用xml配置即可,如果一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用factorybean
例子如下:
1:创建一个car类(是为了简便)一般不能直接给出car类,如果是这样直接注入就可以或者car对象了,这里只是为了简便。
package com.myapp.core.factorybean; public class car { private string make; private int year; public string getmake() { return make; } public void setmake(string make) { this.make = make; } public int getyear() { return year; } public void setyear(int year) { this.year = year; } }
2:一个factorybean的实现拥有创建car
package com.myapp.core.factorybean; import org.springframework.beans.factory.factorybean; public class mycarfactorybean implements factorybean<car>{ private string make; private int year; public void setmake(string make) { this.make = make; } public void setyear(int year) { this.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){ car.setyear(this.year); } if("make".equals(make)){ car.setmake("we are making bla bla bla"); }else{ car.setmake(this.make); } return car; } @override public class<?> getobjecttype() { // todo auto-generated method stub return car.class; } @override public boolean issingleton() { // todo auto-generated method stub return false; } }
以上中创建car太简单了,如果太简单就没有必要用factorybean创建了,可以写的复杂些。
3:person 引用一个car
package com.myapp.core.factorybean; public class person { private car car; public car getcar() { return car; } public void setcar(car car) { this.car = car; } public string tostring(){ return car.getmake()+"::::"+car.getyear(); } }
4:配置引用xml格式:
<bean id="car" class="com.myapp.core.factorybean.mycarfactorybean"> <property name="make" value="makeing car"/> <property name="year" value="123"/> </bean> <bean id="person" class="com.myapp.core.factorybean.person"> <property name="car" ref="car"/> </bean>
5:编写测试类测试:
package com.myapp.core.factorybean; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public class maintest { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("resource/others.xml"); person person = (person)context.getbean("person"); // car car = (car)context.getbean("car"); // system.out.println(car); system.out.println(person); } }
测试结果 makeing car::::123
利用factorybean创建car成功
只是为了说明思想。因为这个接口太重要了。在spring中有很多类实现了该接口。
以上所述是小编给大家介绍的详解spring中的factorybean,希望对大家有所帮助
上一篇: 如何备份MySQL数据库
下一篇: Android图片压缩上传之基础篇