• Spring4.0学习笔记(7) —— 通过FactoryBean配置Bean


    1、实现Spring 提供的FactoryBean接口

    package com.spring.facoryBean;
    
    import org.springframework.beans.factory.FactoryBean;
    
    public class CarFactoryBean implements FactoryBean<Car> {
    
        private String brand;
        
        public void setBrand(String brand) {
            this.brand = brand;
        }
    
        public Car getObject() throws Exception {
            return new Car(brand);
        }
    
        public Class<?> getObjectType() {
            return Car.class;
        }
    
        public boolean isSingleton() {
            return true;
        }
    }

    2、配置xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
    
        <!-- 
            通过FactoryBean 来配置Bean 的实例
            class : 指向FactoryBean的全类名
            property : 配置FactoryBean的属性
            
            实际返回的是FactoryBean 的 getObject 方法的得到的实例
        
         -->
        <bean id="car" class="com.spring.facoryBean.CarFactoryBean">
            <property name="brand" value="BMW"></property>
        </bean>
    </beans>

    3、bean文件

    package com.spring.facoryBean;
    
    public class Car {
        
        public Car(String brand) {
            this.brand = brand;
        }
    
        @Override
        public String toString() {
            return "Car [brand=" + brand + "]";
        }
    
        private String brand;
        
        public void setBrand(String brand){
            System.out.println("setBrand...");
            this.brand = brand;
        }
        
        public void init(){
            System.out.println("init...");
        }
        
        public void destroy(){
            System.out.println("destroy...");
        }
        
    }

    4、main方法实现

    package com.spring.facoryBean;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class main {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-beanFactory.xml");
            Car car = (Car)ctx.getBean("car");
            System.out.println(car);
        }
    }
  • 相关阅读:
    php public protected private属性实例详解
    php 获取代码执行时间和消耗的内存
    php使用位与运算符【&】或【|】实现权限管理
    jquery checkbox选中、改变状态、change和click事件
    PHP设置脚本最大执行时间的三种方法
    Windows上node.js的多版本管理工具
    win10家庭版安装Docker for Windows
    spring boot读取Excel
    JAVA泛型知识--> <? extends T>和<? super T>
    D3.js的v5版本入门教程(第十三章)—— 饼状图
  • 原文地址:https://www.cnblogs.com/cklovefan/p/5300268.html
Copyright © 2020-2023  润新知