1.package spring.chapter2.setDemo;
2.import org.springframework.context.ApplicationContext;
3.import org.springframework.context.support.ClassPathXmlApplicationContext;
4.
5.
6.public class SpringTest {
7.public static void main(String args[]){
8. ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
9. Role role =(Role)ac.getBean("role");
10. System.out.println("人物名称:"+role.getName()+" 血量: "+role.getHealth());
11.}
12.package spring.chapter2.setDemo;
13.import java.lang.reflect.*;
14.import org.springframework.beans.BeansException;
15.import org.springframework.beans.factory.config.BeanPostProcessor;
16.
17.public class HealthModifier implements BeanPostProcessor {
18./*//游戏外挂么!@
19. *
20. *
21. *
22. *
23. *
24. *
25.*/ public Object postProcessAfterInitialization(Object bean,String name)throws BeansException
26. {
27. //获取bean中所有的属性
28. Field[] fields =bean.getClass().getDeclaredFields();
29. for(int i=0;i<fields.length;i++)
30. //由于role中只有一个int字段且就是health,这里只需要进行一个简单的类型判断
31. if(fields[i].getType().equals(int.class)){
32. //这句非常重要,因为Role中所有字段是private的,这里设置可以访问
33. fields[i].setAccessible(true);
34. try{
35. //获得系统设定的health值
36. int health =(Integer)fields[i].get(bean);
37. //修改人物生命值,增加100
38. fields[i].set(bean,health+300);
39. }catch(IllegalAccessException e)
40. {
41. e.printStackTrace();
42. }
43. }
44.
45. System.out.println("****after******");
46.
47. return bean;
48. }
49.
50. @Override
51. public Object postProcessBeforeInitialization(Object bean, String beanName)
52. throws BeansException {
53. // TODO Auto-generated method stub
54. System.out.println("++++before++");
55. return bean;
56.
57. }
58.
59.}
60.<?xml version="1.0" encoding="UTF-8"?>
61.<beans xmlns="http://www.springframework.org/schema/beans"
62. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
63. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
64.
65. <bean id="medicine" class="spring.chapter2.setDemo.Medicine">
66. <property name="name" value="小药丸" />
67. <property name="blood" value="10" />
68. </bean>
69. <bean id="role" class="spring.chapter2.setDemo.Role">
70. <property name="name" value="Mary" />
71. <property name="health" value="100" />
72. <property name="goods">
73. <list>
74. <ref bean="medicine" />
75. </list>
76. </property>
77. </bean>
78.
79. <bean id="healthModifier" class="spring.chapter2.setDemo.HealthModifier"/>
80.</beans>
81.<!-- 在Spring.xml里有几个id 则BeanPostProcessor调用几次 --> }