Spring bean三种创建方式
Posted JustDo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring bean三种创建方式相关的知识,希望对你有一定的参考价值。
spring共提供了三种实例化bean的方式:构造器实例化 静态工厂实例化 动态工厂实例化,下面一一详解:
1、构造器实例化
City.java
1 package com.proc.bean; 2 3 public class City { 4 5 private String name; 6 private String code; 7 8 public City() { 9 } 10 11 public City(String name, String code) { 12 this.name = name; 13 this.code = code; 14 } 15 16 public String getName() { 17 return name; 18 } 19 20 public void setName(String name) { 21 this.name = name; 22 } 23 24 public String getCode() { 25 return code; 26 } 27 28 public void setCode(String code) { 29 this.code = code; 30 } 31 32 @Override 33 public String toString() { 34 return "City [name=" + name + ", code=" + code + "]"; 35 } 36 }
通过构造方式配置Bean
1 <bean id="city" class="com.proc.bean.City"> 2 <constructor-arg value="北京"/> 3 <constructor-arg value="BJ"/> 4 </bean>
测试代码
1 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); 2 City city=ctx.getBean("city", City.class); 3 System.out.println(city);
输出结果
City [name=北京, code=BJ]
2、静态工厂实例化
先创建一个静态工厂StaticCityFactory
1 package com.proc.bean; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class StaticCityFactory { 7 8 private static Map<String, City> cities; 9 10 static{ 11 cities=new HashMap<String, City>(); 12 cities.put("BJ", new City("北京", "BJ")); 13 cities.put("SH", new City("上海", "SH")); 14 cities.put("CD", new City("成都", "CD")); 15 cities.put("SZ", new City("深圳", "SZ")); 16 } 17 18 public static City getCity(String code){ 19 return cities.get(code); 20 } 21 }
配置bean
1 <!-- 通过静态工厂实例化对象 2 class:静态工厂类型 3 factory-method:静态工厂静态方法名称 4 constructor-arg:为静态工厂方法指定参数 5 --> 6 <bean id="city" class="com.proc.bean.StaticCityFactory" factory-method="getCity"> 7 <constructor-arg value="BJ"/> 8 </bean>
3、动态工厂实例化
先创建一个实例化工厂
1 package com.proc.bean; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class InstanceCityFactory { 7 8 private Map<String, City> cities; 9 { 10 cities=new HashMap<String, City>(); 11 cities.put("BJ", new City("北京", "BJ")); 12 cities.put("SH", new City("上海", "SH")); 13 cities.put("CD", new City("成都", "CD")); 14 cities.put("SZ", new City("深圳", "SZ")); 15 } 16 17 public City getCity(String code){ 18 return cities.get(code); 19 } 20 }
配置
1 <!-- 配置实例化工厂 --> 2 <bean id="cityFacotry" class="com.proc.bean.InstanceCityFactory"/> 3 4 <!-- 通过实例化工厂获取对象 --> 5 <bean id="city" factory-bean="cityFacotry" factory-method="getCity"> 6 <constructor-arg value="SH"/> <!-- 配置参数 --> 7 </bean>
以上是关于Spring bean三种创建方式的主要内容,如果未能解决你的问题,请参考以下文章