Java

Spring基于xml配置复杂类Bean

勤劳的小蜜蜂 · 5月13日 · 2019年 · ·

Spring Bean的配置方法有三种:

  • 基于XML的配置方式(主要使用于第三方类库
  • 基于注解的配置方式(实现类是当前项目开发的,可直接在Java类中使用注解配置)
  • 基于Java类的配置方式(实例化Bean的逻辑比较复杂

日常的开发中主要是使用XML配置和注解配置方式结合的开发方式,一般不推荐使用基于Java类的配置方式。

复杂成员的Pojo

import java.util.*;
public class ComplexAssembly {
	private int id;
	private List<String> list;
	private Map<String, String> map;
	private Properties props;
	private Set<String> set;
	private String[] array;

        /* 此处省略Getters and Setters和toString */

xml配置Bean

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<bean id="complexAssembly" class="com.ye.xml.ComplexAssembly">
		<property name="id" value="1"></property>
		
		<property name="list">
			<list>
				<value>list1</value>
				<value>list2</value>
				<value>list3</value>
			</list>
		</property>
		
		<property name="map">
			<map>
				<entry key="key1" value="value1" />
				<entry key="key2" value="value2" />
				<entry key="key3" value="value3" />
			</map>
		</property>
		
		<property name="props">
			<props>
				<prop key="pkey1">pvalue1</prop>
				<prop key="pkey2">pvalue2</prop>
				<prop key="pkey3">pvalue3</prop>
			</props>
		</property>
		
		<property name="set">
			<set>
				<value>set1</value>
				<value>set2</value>
				<value>set3</value>
			</set>
		</property>
		
		<property name="array">
				<array>
					<value>array1</value>
					<value>array2</value>
					<value>array3</value>
				</array>	
		</property>
	
	</bean>
</beans>

测试

/* 此处省略包和引用 */
public class Main {

	public static void main(String[] args) {
		ApplicationContext context= new ClassPathXmlApplicationContext("spring-cfg-4.xml");
		ComplexAssembly ca = (ComplexAssembly) context.getBean("complexAssembly");
		System.out.println(ca);
	}
}

测试结果

ComplexAssembly [
 array=[array1, array2, array3],
 id=1, list=[list1, list2, list3],
 map={key1=value1, key2=value2, key3=value3},
 props={pkey3=pvalue3, pkey1=pvalue1, pkey2=pvalue2},
 set=[set1, set2, set3]
]

0 条回应