Spring Bean 高级装配

applicationcontext

<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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="bean" class="com.zxiaoyao.beans2.Bean" abstract="true">
		<property name="name" value="张三" />
		<property name="age" value="100" />
	</bean>
	
	<!-- 抽象基bean类型 -->
	<bean id="bean1" class="com.zxiaoyao.beans2.Bean1" parent="bean"/>
	<!-- 覆盖继承属性 -->
	<bean id="bean2" class="com.zxiaoyao.beans2.Bean1" parent="bean">
		<property name="name" value="李四"></property>
	</bean>
	<bean id="bean3" class="com.zxiaoyao.beans2.Bean1" parent="bean">
		<property name="name" value="王二麻子"></property>
	</bean>
	
	<!-- 方法注入 -->
	<!-- 1方法替换:在运行时用心的实现替换现有的方法(抽象或具体的) -->
	<bean id="bean4" class="com.zxiaoyao.beans2.Bean3"></bean>
	<bean id="bean5" class="com.zxiaoyao.beans2.Bean2">
		<replaced-method
			name="toString"
			replacer="bean4"/>
	</bean>
	<!-- 获取器注入 -->
	<bean id="bean6" class="com.zxiaoyao.beans2.Bean4">
		<lookup-method name="getBean" bean="bean5"/>
	</bean>
	
	<!-- Spring 本身的 自定义属性编辑器 能够自动把注入的String值转化为更复杂的类型 -->
	<!-- ClassEditor				| 以一个String值设置java.lang.Class属性,前者包含一个完整描述的类名 -->
	<!-- CunstomDateEditor	 		| 以一个String值设置java.util.Date属性,前者使用自定义的java.text.DateFormat对象 -->
	<!-- FileEditor					| 以一个String值设置java.io.File属性,前者包含文件的路径  -->
	<!-- LocalEditor 				| 以一个String值设置java.util.Locale属性,前者包含地域的文本表示(比如zh_cn)-->
	<!-- StringArrayPropertyEditor 	| 把逗号分隔的String转化为一个String数组属性-->
	<!-- StringTrimmer				| 对String属性进行自动裁剪,设置一个选项后可以把空的String值转化为null -->
	<!-- URLEditor					| 以一个String值设置java.net.URL属性,前者包含一个URL -->
	
	<!-- 设置自定义 属性编辑器 -->
	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map >
				<entry key="com.zxiaoyao.beans2.PhoneNumber">
					<bean id="phoneEditor" class="com.zxiaoyao.beans2.PhoneEditor" />
				</entry>
			</map>
		</property>
	
	</bean>
	<bean id="contact" class="com.zxiaoyao.beans2.Contact">
		<property name="phone" value="029-88332233"></property>
	</bean>
	<!-- end 设置自定义 属性编辑器 -->
	
	<!-- 因此类实现了BeanPostProcessor接口,在此配置为bean后 会被容器识别为BeanPostProcessor,在容器里的每个bean被初始化之前和之后调用后处理方法  -->
	<bean class="com.zxiaoyao.beans2.BeanProcessor"></bean>
	<bean id="bean7" class="com.zxiaoyao.beans2.Bean1" parent="bean">
		<property name="name" value="张 三  李 四  " />
	</bean>
	
	<!-- 类实现BeanFactoryPostProcessor 后 在容器注册,容器会自动把她注册为Bean工厂后处理器。BeanFactoryPostProcessor 不能用户基本的Bean工厂容器。
	            这个特性 只能用于上下文容器(ApplicationContext)-->
	<bean class="com.zxiaoyao.beans2.BeanCounter"></bean>
	
	<!-- 提取文本 消息,id必须为messageSource applicationcontext 在建立内部消息源时会查找名称为:messageSource 的bean -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename">
			<value>msg</value>
		</property>
	</bean>
</beans>


相关bean 去掉 set get toString方法

public abstract class Bean{
	private String name;
	private int age;
//-----------------------------------------------
public  class Bean1 extends Bean{
	private String name;
	private int age;
//----------------------------------------------
public  class Bean2 extends Bean{
	@Override
	public String toString() {
		return "这是 Bean2。。。。";
	}
}
//---------------------------------------------
public class Bean3 implements MethodReplacer{
	public Object reimplement(Object obj, Method method, Object[] args)
			throws Throwable {
		return "替代品。。。";
	}
}
//-----------------------------------------------
public  abstract class Bean4 extends Bean {
	@Override
	public String toString() {
		return getBean().toString();
	}
	public abstract Bean getBean();
}
//---------------------------------------------
/**
 * Bean工厂的后处理
 *
 *BeanFactoryProcessor 的 接口实现会在全部Bean定义被夹在后,但在任何一个Bean被实例化之前
 *(包括BeanFactoryProcessor Bean),Spring容器会调用postProcessBeanFactory()方法
 *
 * @author zxy
 */
public class BeanCounter implements BeanFactoryPostProcessor {
	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("beanFactory.getBeanDefinitionCount():"+beanFactory.getBeanDefinitionCount());
	}
}
//-----------------------------------------------
/**
 * 后处理Bean
 *  
 * 此类实现了BeanPostProcessor接口,
 * 注册后 会被容器识别为BeanPostProcessor,
 * 在容器里的每个bean被初始化之前和之后调用后处理方法
 *
 */
public class BeanProcessor implements BeanPostProcessor {
	/**
	 * 初始化后处理
	 */
	public Object postProcessAfterInitialization(Object bean, String name)
			throws BeansException {
		System.out.println("bean 后处理");
		Field[] fields = bean.getClass().getDeclaredFields();
		
		try {
			for(int i=0;i < fields.length; i++){
				if(fields[i].getType().equals(String.class)){
					fields[i].setAccessible(true);
					String s = (String)fields[i].get(bean);
					fields[i].set(bean, trimStr(s));
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return bean;
	}
	private String trimStr(String data){
		if(data == null ){
			return "null";
		}
		data = data.trim();
		data = data.replaceAll(" ", "");
		if("".equals(data)){
			return "null";
		}
		return data;
	}
	/**
	 * 初始化前处理
	 */
	public Object postProcessBeforeInitialization(Object arg0, String arg1)
			throws BeansException {
		System.out.println("bean 前处理。。。");
		return arg0;
	}
}
//-----------------------------------------------
public class Contact {
	private PhoneNumber phone;
//----------------------------------------------
public class PhoneEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		String[] phonedata = stripData(text);
		if(phonedata[0] != null){
			PhoneNumber phone = new PhoneNumber(phonedata[0],phonedata[1]);
			setValue(phone);
		}
	}
	//将字符串解析为PhoneNubmer对象
	private String[] stripData(String data){
		String[] reStrs = new String[2];
		String[] ss = data.split("-");
		for(int i=0; i<reStrs.length; i++){
			StringBuilder s = new StringBuilder();
			for(int j=0;j<ss[i].length();j++){
				char c  = ss[i].charAt(j);
				if(Character.isDigit(c)){
					s.append(c);
				}
			}
			reStrs[i] = s.toString();
		}
		return reStrs;
	}
}
//---------------------------------------------
public class PhoneNumber {
	private String quhao;
	private String number;
public PhoneNumber(String quhao, String number) {
		super();
		this.quhao = quhao;
		this.number = number;
	}

test方法

public static void test2(){
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
		Bean1  b1 = (Bean1)context.getBean("bean1");
		System.out.println(b1);
		Bean1 b2 = (Bean1)context.getBean("bean2");
		System.out.println(b2);
		Bean1 b3 = (Bean1)context.getBean("bean3");
		System.out.println(b3);
		Bean2 b5 = (Bean2) context.getBean("bean5");
		System.out.println(b5);
		Bean4 b6 =(Bean4)context.getBean("bean6");
		System.out.println(b6);
		Contact c = (Contact) context.getBean("contact");
		System.out.println(c.getPhone());
		Bean1 b7 = (Bean1)context.getBean("bean7");
		System.out.println(b7);
		/**
		 * 通过getMessage方法访问消息源
		 */
		System.out.println(context.getMessage("name", new Object[0], Locale.getDefault()));
		System.out.println(context.getMessage("name", new Object[0], Locale.CHINA));
		System.out.println(context.getMessage("name", new Object[0], Locale.TAIWAN));
		System.out.println(context.getMessage("name", new Object[0], Locale.US));
	}



原文地址:https://www.cnblogs.com/hlantian/p/10194573.html