简体   繁体   English

Java Bean实例化错误的Bean

[英]Java Beans instantiating wrong bean

In my Spring-Module.xml I have two beans: 在我的Spring-Module.xml中,我有两个bean:

<bean id="two_num" class="main.java.com.shen.Generator">
    <property name="length" value="8" />
    <property name="categories" value="3" />
    ...
</bean>
<bean id="six_num" class="main.java.com.shen.Generator">
    <property name="length" value="6" />
    <property name="categories" value="1" />
    <property name="numeric" value="numeric" />
    ...
</bean>

And I instantiate my class like so: 我像这样实例化我的班级:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
    Generator obj = (Generator) context.getBean("two_num");

For some reasons, java is always instantiating my second bean despite me explicitly saying that I want the bean "two_num". 由于某些原因,尽管我明确表示我想要bean“ two_num”,但java总是实例化我的第二个bean。 If I were to flip the order around, and have "six_num"'s bean above "two_num", it would get the bottom bean. 如果我要翻转订单,并将“ six_num”的bean放在“ two_num”之上,它将得到底部的bean。 :| :| What's going on? 这是怎么回事? I'm so confused. 我很混乱。 Is my method for selecting a specific bean wrong? 我选择特定bean的方法是否错误?

EDIT: after adding one more bean to it this is what I get when I run my program: 编辑:向其中添加一个更多的bean之后,这就是我运行程序时得到的:

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@e949f69: defining beans [two_num,six_num,four_num]; INFO:在org.springframework.beans.factory.support.DefaultListableBeanFactory@e949f69中预实例化单例:定义bean [two_num,six_num,four_num]; root of factory hierarchy 工厂层次结构的根

And as expected, when I call a print method in my class, I can see that the current object is instantiated with the information dicated in four_num, and not "two_num" 正如预期的那样,当我在类中调用一个print方法时,我可以看到当前对象是用four_num(而不是“ two_num”)指定的信息实例化的。

Certainly remove static modifiers on your fields, as already suggested. 如已经建议的,当然可以删除字段上的静态修饰符。 Also, if you want 'singletons' modify your XML: 另外,如果要“单项”修改XML,请执行以下操作:

<bean id="two_num" class="main.java.com.shen.Generator" scope="singleton">
  <property name="length" value="8" />
  <property name="categories" value="3" />
  ...
</bean>

So you'll only get a single instance of each bean. 因此,您只会获得每个Bean的单个实例。 You'll still get multiple instances of Generator, but only one per bean. 您仍将获得Generator的多个实例,但每个bean仅一个。

Based on comments, I can only assume that the Generator class looks something like this 基于注释,我只能假设Generator类看起来像这样

public class Generator {
  private static length;
  private static categories;

  //getters/setters
}

Given that i dont have a full class to work with, i can only recommend removing the static modifier as it would contradict the way you want to use the class. 鉴于我没有一个完整的类可以使用,我只能建议删除static修饰符,因为它会与您要使用该类的方式相矛盾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM