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

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 CarFactoryBean implements FactoryBean<Car>{

 

      private String brand;

     

      publicvoidsetBrand(String brand) {

            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

      publicboolean isSingleton(){

            // TODO Auto-generated method stub

            returntrue;

      }

     

 

}

配置app.xml内容如下

      <bean id="carFactory"class="CarFactoryBean">

            <property name="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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值