zoukankan      html  css  js  c++  java
  • spring FactoryBean配置Bean

    概要:



    实例代码具体解释:

    文件夹结构



    Car.java

    package com.coslay.beans.factorybean;
    
    public class Car {
    	private String brand;
    	private double price;
    
    	public String getBrand() {
    		return brand;
    	}
    
    	public void setBrand(String brand) {
    		this.brand = brand;
    	}
    
    	public double getPrice() {
    		return price;
    	}
    
    	public void setPrice(double price) {
    		this.price = price;
    	}
    
    	@Override
    	public String toString() {
    		return "Car [brand=" + brand + ", price=" + price + "]";
    	}
    
    	public Car() {
    		System.out.println("Car's Constructor...");
    	}
    
    	public Car(String brand, double price) {
    		super();
    		this.brand = brand;
    		this.price = price;
    	}
    
    }
    


    CarFactoryBean.java

    package com.coslay.beans.factorybean;
    
    import org.springframework.beans.factory.FactoryBean;
    
    
    //自己定义的FactoryBean须要实现 FactoryBean接口
    public class CarFactoryBean implements FactoryBean<Car>{
    
    	private String brand;
    	
    	public void setBrand(String brand){
    		this.brand = brand;
    	}
    	
    	//返回bean的对象
    	@Override
    	public Car getObject() throws Exception {
    		return new Car("BMW",5000000);
    	}
    	
    	//返回bean的类型
    	@Override
    	public Class<?> getObjectType() {
    		return Car.class;
    	}
    
    	@Override
    	public boolean isSingleton() {
    		return true;
    	}
    	
    }
    


    Main.java

    package com.coslay.beans.factorybean;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Main {
    	public static void main(String[] args) {
    		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-beanfactory.xml");
    		Car car = (Car) ctx.getBean("car");
    		System.out.println(car);
    	}
    }
    


    beans-beanfactory.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过FactoryBean来配置Bean的实例 class:指向FactoryBean的全类名 property:配置FactoryBean的属性 但实际返回的实例确是FactoryBean的getObject()方法返回的实例 --> <bean id="car" class="com.coslay.beans.factorybean.CarFactoryBean"> <property name="brand" value="BMW"></property> </bean> </beans>



  • 相关阅读:
    C# decimal保留指定的小数位数,不四舍五入
    C# :实现水印与图片合成,并利用Graphics 压缩图像质量 , (委托实现listBox的动态添加提示)
    手机游戏模拟器汇总 用于开发
    WinAPI 操作串口
    C#图片压缩算法
    SQL SERVER 2008 无法启动TSQL调试的解决方法
    C#放缩、截取、合并图片并生成高质量新图的类
    C#图片处理之: 另存为压缩质量可自己控制的JPEG
    URL及short URL短网址
    1的补码及2的补码
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6740207.html
Copyright © 2011-2022 走看看