欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java,

来源: javaer 分享于  点击 14064 次 点评:141

java,


package spring.chapter2.setDemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringTest {
public static void main(String args[]){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	Role role =(Role)ac.getBean("role");
	System.out.println("人物名称:"+role.getName()+"   血量: "+role.getHealth());
}
package spring.chapter2.setDemo;
import java.lang.reflect.*;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class HealthModifier implements BeanPostProcessor {
/*//游戏外挂么!@
 * 
 * 
 * 
 * 
 * 
 * 
*/	public Object postProcessAfterInitialization(Object bean,String name)throws BeansException
	{
		//获取bean中所有的属性
		Field[] fields =bean.getClass().getDeclaredFields();
		for(int i=0;i<fields.length;i++)
			//由于role中只有一个int字段且就是health,这里只需要进行一个简单的类型判断
			if(fields[i].getType().equals(int.class)){
				//这句非常重要,因为Role中所有字段是private的,这里设置可以访问
				fields[i].setAccessible(true);
				try{
					//获得系统设定的health值
					int health =(Integer)fields[i].get(bean);
					//修改人物生命值,增加100
					fields[i].set(bean,health+300);
				}catch(IllegalAccessException e)
				{
					e.printStackTrace();
				}
			}
		
		System.out.println("****after******");

		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		// TODO Auto-generated method stub
		System.out.println("++++before++");
		return 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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="medicine" class="spring.chapter2.setDemo.Medicine">
		<property name="name" value="小药丸" />
		<property name="blood" value="10" />
	</bean>
	<bean id="role" class="spring.chapter2.setDemo.Role">
		<property name="name" value="Mary" />
		<property name="health" value="100" />
		<property name="goods">
			<list>
				<ref bean="medicine" />
			</list>
		</property>
	</bean>

	<bean id="healthModifier" class="spring.chapter2.setDemo.HealthModifier"/>
</beans>
<!-- 在Spring.xml里有几个id  则BeanPostProcessor调用几次 -->  }
 

相关文章

    暂无相关文章
相关栏目:

用户点评