java相关:详解Spring中的FactoryBean

发布于 2020-12-30|标签java
复制链接
本篇文章主要介绍了Spring中的FactoryBean,如果一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean
spring  FactoryBean 是创建 复杂的bean,一般的bean 直接用xml配置即可,如果一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean例子如下: 1:创建一个Car类(是为了简便)一般不能直接给出Car类,如果是这样直接注入就可以或者Car对象了,这里只是为了简便。 ```java 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 ```java package com.myapp.core.factorybean; import org.springframework.beans.factory.FactoryBean; public class MyCarFactoryBean implements FactoryBean{ 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 ```java 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格式: ```xml ``` 5:编写测试类测试: ```java 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中有很多类实现了该接口。 原文地址: http://blog.csdn.net/topwqp/article/details/8678061
冀ICP备17029012号-4 | 版权所有©鲍亚龙 |免责声明  | GIF图库  | NUXT版