16.笔记JAVA Spring框架学习————通过FactoryBean配置Bean

来源:互联网 发布:淘宝新店能开通直播吗 编辑:程序博客网 时间:2024/05/16 01:27

16.笔记JAVA Spring框架学习————通过FactoryBean配置Bean

•       Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.

•       工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象

通过FactoryBean来配置Bean的示例,class指向F

创建一个类CarFactoryBean实现接口FactoryBean的全类目,property配置FactoryBean的属性。

import org.springframework.beans.factory.FactoryBean;

 

publicclass CarFactoryBeanimplements FactoryBean<Car>{

 

      private Stringbrand;

     

      publicvoidsetBrand(Stringbrand) {

            this.brand = brand;

      }

      @Override

      public Car getObject()throws Exception {

            //TODO Auto-generated method stub

            returnnew Car(brand,40000);

      }

 

      @Override

      publicClass<?> getObjectType() {

            //TODO Auto-generated method stub

            return Car.class;

      }

 

      @Override

      publicbooleanisSingleton(){

            //TODO Auto-generated method stub

            returntrue;

      }

     

 

}

配置app.xml内容如下

      <beanid="carFactory"class="CarFactoryBean">

            <propertyname="brand"value="bmw"></property>

      </bean>

然后配置main.java如下

import java.sql.SQLException;

 

import javax.sql.DataSource;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.AbstractApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

import com.mchange.v2.c3p0.DataSources;

 

public class Main {

                 

                  publicstatic void main(String[] args) throws SQLException {

                                   

                 

                                    //1.创建 Spring IOC容器

                                    ClassPathXmlApplicationContextapx = new ClassPathXmlApplicationContext("app.xml");

                                    Carcar = (Car) apx.getBean("carFactory");

                                    System.out.println(car);

                  }

                 

}

指向如下:

Car[company=bmw, brand=null, maxSpeed=0, price=40000.0]

 

 

 

 

阅读全文
0 0
原创粉丝点击