java - 使用Spring框架的构造函数依赖注入(inject),无法保留值

标签 java xml spring javabeans

这是 XML 文件 bean-jojo.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


        <bean id="vTypeCar" class="com.justPractise.ex01.Car" />
        <bean id="vTypeBike" class="com.justPractise.ex01.MotorCycle" />        

        <bean id="vService" class="com.justPractise.ex01.VehicalService">
            <property name="vehical" ref="vTypeBike" />
        </bean>     

        <bean id="beanLifeCycleTest" class="com.jal.LifeCycleBeanP2">
            <property name="justAParam" value="MICHEAL JACKSON" />
        </bean>     

        <bean id="brun-p" class="com.justPractise.ex01.HALBrunPojo">
            <constructor-arg value="234" />
        </bean>                 
</beans>

我已经注册了以下 bean,我正在其上尝试构造函数 DI:

package com.justPractise.ex01;

public class HALBrunPojo {

    private Integer num;

    public HALBrunPojo(){
        System.out.println(this.getClass().getName()+" INITIALISED ");
    }

    public HALBrunPojo(int num){
        System.out.println(this.getClass().getName()+" PARAMETERISED..... INITIALISED "+num);
        this.num = num;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

}

如上述 bean 声明的 XML 所示,我已指定构造函数参数, 现在使用以下代码,其中包含 main 方法:

package com.justPractise.ex01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainPractise01 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext ctx = null;      
        HALBrunPojo obj = null;
        try{
            ctx = new ClassPathXmlApplicationContext("bean-jojo.xml");
            obj = (HALBrunPojo) ctx.getBean("brun-p");
            System.out.println(" PARAM-VALUE "+(obj == null ? "0" : obj.getNum()));
        }catch(Exception e){
            e.printStackTrace();            
        }
    }

}

当我尝试从命令行运行上述类时,输出为

PARAM-VALUE 0

这意味着 HALBrunPojonull。经过调试我发现,如果我在bean-jojo.xml中注释掉LifeCycleBeanP2的bean声明,如下所示:

        <!--
        <bean id="beanLifeCycleTest" class="com.jal.LifeCycleBeanP2">
            <property name="justAParam" value="MICHEAL JACKSON" />
        </bean>     
        -->

然后我运行程序,得到所需的输出,即

PARAM-VALUE 234

为什么会这样?,这是bean的代码LifeCycleBeanP2.java:

package com.jal;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class LifeCycleBeanP2 implements BeanNameAware, BeanFactoryAware, BeanPostProcessor, InitializingBean, DisposableBean{
    String justAParam;

    public LifeCycleBeanP2(){
        System.out.println(this.getClass().getName()+" INITIALISED...... ");
    }

    public String getJustAParam() {
        return justAParam;
    }

    public void setJustAParam(String justAParam) {
        System.out.println(" SETTER OF JustAParam ........ ");
        this.justAParam = justAParam;
    }

    // method of BeanNameAware
    @Override
    public void setBeanName(String arg0) {
        System.out.println(" IN SET BEAN-NAME "+arg0);
    }

    // method of BeanFactoryAware
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        System.out.println(" IN SET BEAN-FACTORY, "+arg0.getClass().getName());
    }

    // method of BeanPostProcessor
    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println(" POST PROCESS AFTER INITIALISATION ");
        return null;
    }

    // method of BeanPostProcessor
    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println(" POST PROCESS BEFORE INITIALISATION ");
        return null;
    }

    //method of InitializingBean
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(" AFTER PROPERTIES SET ");
    }

    //method of DisposableBean
    @Override
    public void destroy() throws Exception {
        System.out.println(" BEAN "+this.getClass().getName()+" QUALIFIED FOR GARBAGE COLLECTION ");
    }
}

我做错了什么?

最佳答案

实现 BeanPostProcessor 接口(interface)的 bean 是一种特殊的 bean。它传递了对上下文创建的所有其他 bean 的引用,它可以修改它们并在需要时返回不同的实例

BeanPostProcessor 返回的任何引用都将与 bean id 关联。

在您的 LifeCycle 类中,您将返回 null - 相反,您应该返回对传递给您的方法的对象的引用。按如下方式更改这两个方法,它应该可以按预期工作。

   // method of BeanPostProcessor
    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println(" POST PROCESS AFTER INITIALISATION ");
        return arg0;
    }

    // method of BeanPostProcessor
    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println(" POST PROCESS BEFORE INITIALISATION ");
        return arg0;
    }

关于java - 使用Spring框架的构造函数依赖注入(inject),无法保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10535526/

相关文章:

java - 什么是NullPointerException,我该如何解决?

java - 创建类路径资源 [jpaContext.xml] 中定义的名称为 'entityManagerFactory' 的 bean 时出错

php - 使用 PHP XMLReader 检测 XML 自闭标签

java.lang.IllegalStateException : LifecycleProcessor not initialized . ...上下文 - 在我的聊天应用程序上

java - 如何在@Async void 方法中断言异常?

java - 2 个 POST 请求处理程序(ResponseBody + "Normal")

java - Hibernate不会初始化代理

java - 如何在 Java 中隐藏枚举值?

java - 使用 Java 查询 XML

java - 如果条件为 true,则向 spring 表单元素添加属性