我试图在spring IOC中使用java config在同一个bean类型的列表中注入同一个bean的多个实例。但是在列表对象中打印实例的值时,它只显示一个,我没有得到这个代码的错误。但我没有得到理想的输出。我通过删除列表中第一个实例的添加尝试了另一件事,但它只显示了该数据。我的代码是这样的(我正在使用Eclipse Kepler)
JAVA配置代码
package SprLab8InjectOfCollectionAnno;
import java.util.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class springconfigLab8 {
@Bean
public List<String> emails()
{
List<String> emails=new ArrayList();
emails.add("Aman@dittu");
emails.add("Dileep@dittu");
emails.add("Mohit@dittu");
emails.add("Sumit@dittu");
return emails;
}
@Bean
public Set<Long> phones()
{
Set<Long> phones=new LinkedHashSet();
phones.add(1111l);
phones.add(2222l);
phones.add(3333l);
phones.add(4444l);
return phones;
}
@Bean(name="refs")
public Map<String,Long> references()
{
Map<String,Long> ref=new LinkedHashMap();
ref.put("aa", 11l);
ref.put("bb", 22l);
ref.put("cc", 33l);
ref.put("dd", 44l);
return ref;
}
@Bean(name="props")
public Properties myproperties()
{
Properties prop=new Properties();
prop.put("aa", 11l);
prop.put("bb", 22l);
prop.put("cc", 33l);
prop.put("dd", 44l);
return prop;
}
@Bean
public Address address()
{
return new Address("Bangalore","J.P.Nagar","Karnataka");
}
@Bean
public Account account()
{
Account acc=new Account();
acc.setAccno(11);
acc.setAtype("Saving Account");
acc.setBal(10000.0);
return acc;
}
@Bean(name="accounts")
public List<Account> accounts()
{
List<Account> accounts=new ArrayList<Account>();
Account acc2=new Account();
acc2.setAccno(12);
acc2.setAtype("Saving Account");
acc2.setBal(30000.0);
accounts.add(account());//if I am commenting this line then also it is
//showing output for this line only.
accounts.add(acc2);// this line is not working
return accounts;
}
@Bean(name="cust")
public Customer custom(Address addr)
{
Customer custs=new Customer(101,"Dileep","Dileep@dittu",9999l);
custs.setAddress(addr);
return custs;
}
}
/* expected output for Account list is
11 Saving Account 10000
12 Saving Account 30000
but I m getting 11 Saving Account 10000
*/
答案 0 :(得分:0)
如果您的范围是单例,则不能拥有同一个bean的多个实例。 Singleton是默认范围