spring----通过实现FactoryBean接口来配置Bean----笔记

Bean配置文件

<?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"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
		
	<!-- 通过实现FactoryBean接口 配置bean -->
	<bean id="cola" class="top.demo.test.spring2.WaterFactoryBean"></bean>
	
	
</beans>

测试用到的Water类

package top.demo.test.spring2;

public class Water {

	public String name;
	public int price;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public Water(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Water [name=" + name + ", price=" + price + "]";
	}
}

实现FactoryBean的类

package top.demo.test.spring2;

import org.springframework.beans.factory.FactoryBean;

public class WaterFactoryBean implements FactoryBean<Water>{

	@Override
	public Water getObject() throws Exception {
		//获得工厂创建的对象的接口方法
		return new Water("可乐", 4);
	}

	@Override
	public Class<?> getObjectType() {
		// 返回对象的Class
		return Water.class;
	}

	
	@Override
	public boolean isSingleton() {
		// 返回是否是单例的
		//注意这个方法,如果返回true代表单例,即使getObject方法实现时是new(好像是每次调用会有新的地址,但是不是)
//也会得到同一个地址的对象(也就是 是不是单例取决于isSingleton方法,不必奇怪,有反射和动态代理 //框架设计者完全可以做到在getObject之前 检查isSingleton 也可以保存第一次new 出的地址 )
		return true;
	}


}

测试main

package top.demo.test.spring2;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	
	
	public static void main(String argv[]) {
		
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
		
		Water cola=(Water) ctx.getBean("cola");
		System.out.println(cola);
		
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值