使用 BeanPostProcessor 时出现问题。错误日志说 productFactory 类中的方法 josh() 丢失,但该类确实有这样的方法,并且它是非静态的。下面是代码片段。
web.xml
<bean class="demoproject.productPostProcessor" />
<context:annotation-config />
<context:component-scan base-package="demoproject" />
<bean name="ProductFactory" class="demoproject.ProductFactory" />
产品工厂.java
public class ProductCreater{
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("web.xml");
Product copyProduct = (Product) context.getBean("joshs");
System.out.println(copyProduct.getId());
System.out.println(copyProduct.getPrice());
}
}
产品工厂.java
package demoproject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class ProductFactory {
public ProductFactory() {
// TODO Auto-generated constructor stub
}
@Bean(name="joshs")
public Product josh(){
Product josh = new Battery();
josh.setId("cdrw");
return josh;
}
}
productPostProcessor.java
package demoproject;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class productPostProcessor implements BeanPostProcessor{
public Object postProcessBeforeInitialization(Object bean, String beanName){
System.out.println("Before initializing .. : "+beanName);
return beanName;
}
public Object postProcessAfterInitialization(Object bean, String beanName){
System.out.println("After initializing .. : "+beanName);
return beanName;
}
}
错误日志
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7b09df06: defining beans [demoproject.productPostProcessor#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,productFactory,ProductFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,joshs]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'joshs' defined in class path resource [demoproject/ProductFactory.class]: No matching factory method found: factory bean 'ProductFactory'; factory method 'josh()'. Check that a method with the specified name exists and that it is non-static.
不知何故 <bean class="demoproject.productPostProcessor" />
,web.xml 中的行导致了这个问题,因为当我删除它时,一切正常。我怎样才能调试这个程序并修复它?