java代码:
package com.init;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Bean implements BeanPostProcessor {
private String name; /**
 * @return the name
 */
public String getName() {
return name;
} public void init() {
System.out.println("this is init method");
} /**
 * @param name
 *            the name to set
 */
public void setName(String name) {
this.name = name;
} public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("postProcessAfterInitialization");
return arg0;
} public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
System.out.println("postProcessAfterInitialization");
return arg0;
} public void sayHello() {
System.out.println("hello ");
} public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"init.xml");
Bean bean = (Bean) context.getBean("bean");
bean.sayHello();
}}xml文件 :<?xml version="1.0" encoding="GB18030"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
"> <bean id="bean" class="com.init.Bean" init-method="init">
<property name="name">
<value>testName</value>
</property>
</bean></beans>
感谢回复者,祝你连同你的家人快乐。

解决方案 »

  1.   

    也就是方法
    public Object postProcessAfterInitialization(Object arg0, String arg1)
    throws BeansException {
    System.out.println("postProcessAfterInitialization");
    return arg0;
    }public Object postProcessBeforeInitialization(Object arg0, String arg1)
    throws BeansException {
    System.out.println("postProcessAfterInitialization");
    return arg0;
    } 这两个方法没有被调用,是如何回事?
      

  2.   

    一般ApplicationContext会自动检查是否在定义文件中有实现了BeanPostProcessor接口的类,如果有的话,Spring容器会在每个Bean(其他的Bean)被初始化之前和初始化之后,分别调用实现了BeanPostProcessor接口的类的postProcessAfterInitialization()方法和postProcessBeforeInitialization()方法,对Bean进行相关操作。
    但是在楼主的定义文件中,只定义了一个bean,而且还是实现了BeanPostProcessor接口的Bean,我觉得问题应该是出现在这里,建议楼主把现有的Bean分为两个Bean试试,就是一个Bean用来实现BeanPostProcessor接口,然后另一个Bean用来配合实现了BeanPostProcessor接口的Bean。