Getter方法在Spring DI中重新调整null值

时间:2017-09-20 11:33:53

标签: java spring dependency-injection getter-setter

我正在尝试测试Spring Dependency Injection功能,但在尝试使用Spring Bean类的getter方法检索实例变量的值时会遇到问题。获取先前设置的实例变量的空值。

我的主要课程

public class Main {
public static void main(String ... args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("BeanFactory.xml");
    IBackup dataWriterObj = (IBackup) context.getBean("writeBackupHDFS");
    backup backup = new backup();
   backup.setNickName("Abbey");
    String result = dataWriterObj.read("Ankur", "Bahre");
System.out.println(result);
}
}

Bean类

public class backup implements IBackup {
private String nickName;

public String getNickName() {
    return nickName;
}

public void setNickName(String nickName) {
    this.nickName = nickName;
}

public String read(String firstName, String lastName) {
    String Name = "My Name is " + firstName + " " + lastName + " and my nickName is "  + getNickName();
    return Name;
}
}

接口

public interface IBackup {

public String read(String firstName, String lastName);
}

BeanFactory.xml

<bean id="writeBackupHDFS" class="test.backup"/>

预期输出 - My Name is Ankur Bahre and my nickName is Abbey

实际输出 - My Name is Ankur Bahre and my nickName is null

有人能说出我错过的是什么吗?

由于

1 个答案:

答案 0 :(得分:0)

使用backup.setNickName("Abbey")代替 backup backup = new backup(); backup.setNickName("Abbey");

因为下面的代码与dataWriterObj对象无关。

public class Name {
    private String nickName;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
}

编辑:

创建另一个名为

的类
public class backup implements IBackup {

    @Autowired
    Name nameObj;   

    public void setNameObj(Name nameObj) {
        this.nameObj = nameObj;
    }

    public String read(String firstName, String lastName) {
        String Name = "My Name is " + firstName + " " + lastName + " and my nickName is "  + nameObj.getNickName();
        return Name;
    }
}

使用上述更改

更新备份类
 <bean id="writeBackupHDFS" class="springboot.rest.backup">
            <property name="nameObj" ref="nameBean"/>
           </bean>
<bean id="nameBean" class="springboot.rest.Name"/>

将其添加到配置文件BeanFactory.xml:

    ApplicationContext context = new ClassPathXmlApplicationContext("BeanFactory.xml");
        IBackup dataWriterObj = (IBackup) context.getBean("writeBackupHDFS");
        Name nameBean = (Name) context.getBean("nameBean");
     //   backup backup = new backup();
        nameBean.setNickName("Abbey");
        String result = dataWriterObj.read("Ankur", "Bahre");
    System.out.println(result);

现在使用以下代码

更新main方法
{{1}}