📜  具有非字符串映射的Spring Setter注入

📅  最后修改于: 2020-12-04 07:47:10             🧑  作者: Mango

使用非字符串映射(具有依赖对象)的Setter注入示例

在此示例中,我们将地图用作具有Answer和User的答案。在这里,我们将键和值对都用作对象。答案具有自己的信息,例如answerId,答案和postedDate,用户具有自己的信息,例如userId,用户名,emailId。

像前面的示例一样,它是论坛的示例,其中一个问题可以有多个答案

此类包含三个属性,即getters&setters和displayInfo()方法以显示信息。

package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class Question {
private int id;
private String name;
private Map answers;

//getters and setters


public void displayInfo(){
    System.out.println("question id:"+id);
    System.out.println("question name:"+name);
    System.out.println("Answers....");
    Set> set=answers.entrySet();
    Iterator> itr=set.iterator();
    while(itr.hasNext()){
        Entry entry=itr.next();
        Answer ans=entry.getKey();
        User user=entry.getValue();
        System.out.println("Answer Information:");
        System.out.println(ans);
        System.out.println("Posted By:");
        System.out.println(user);
    }
}
}

package com.javatpoint;

import java.util.Date;

public class Answer {
private int id;
private String answer;
private Date postedDate;
public Answer() {}
public Answer(int id, String answer, Date postedDate) {
    super();
    this.id = id;
    this.answer = answer;
    this.postedDate = postedDate;
}

public String toString(){
    return "Id:"+id+" Answer:"+answer+" Posted Date:"+postedDate;
}
}

package com.javatpoint;

public class User {
private int id;
private String name,email;
public User() {}
public User(int id, String name, String email) {
    super();
    this.id = id;
    this.name = name;
    this.email = email;
}

public String toString(){
    return "Id:"+id+" Name:"+name+" Email Id:"+email;
}
}

entry元素key-refvalue-ref属性用于定义映射中bean的引用。






































此类从applicationContext.xml文件获取Bean,并调用displayInfo()方法以显示信息。

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {
public static void main(String[] args) {
    Resource r=new ClassPathResource("applicationContext.xml");
    BeanFactory factory=new XmlBeanFactory(r);
    
    Question q=(Question)factory.getBean("q");
    q.displayInfo();
    
}
}