欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring----通过静态/实例工厂配置bean----笔记

程序员文章站 2022-05-21 23:02:32
...

spring bean配置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"
	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">

	<!-- xmlns:context命名空间 导入非spring的配置文件的内容 -->
	<context:property-placeholder location="classpath:test.properties" />
	
	<util:list id="list">
		<value>${user}</value>
		<value>${pass}</value>
		<value>借助list测试下导入 不写额外的bean了</value>
	</util:list>
	
	<!-- 静态工厂配置bean -->
	<bean id="wahaha" class="top.demo.test.spring2.WaterFactory" factory-method="getStaticWater">
		<constructor-arg name="name" value="娃哈哈"></constructor-arg>
		<constructor-arg name="price" value="4" type="int"></constructor-arg>
	</bean>
	
	<!-- 需要实例化的工厂 配置bean 即先需要创建工厂本身再调用 -->
	<!-- 先配置工厂的实例 -->
	<bean id="insfactory" class="top.demo.test.spring2.InsWaterFactory"></bean>
	<!-- 再通过实例工厂来配置bean -->
	<bean id="kang" factory-bean="insfactory" factory-method="getWater">
		<constructor-arg name="name" value="康师傅"></constructor-arg>
		<constructor-arg name="price" value="3" type="int"></constructor-arg>
	</bean>
	
	
</beans>

测试的 工厂生产的类

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 + "]";
	}
}

静态工厂

package top.demo.test.spring2;

public class WaterFactory {
	
	public static Water getStaticWater(String name,int price) {	
		System.out.println("static WaterFactory create water");
		return new Water(name,price);	
	}

	
	
}

需要实例化的工厂

package top.demo.test.spring2;

public class InsWaterFactory {
	
	public Water getWater(String name,int price) {
		
		System.out.println(" Instance WaterFactory create water");
		return new Water(name,price);	
		
	}

}