Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11335

Java Beans instantiating wrong bean

In my Spring-Module.xml I have two beans:

<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". If I were to flip the order around, and have "six_num"'s bean above "two_num", it would get the bottom bean. :| What's going on? I'm so confused. Is my method for selecting a specific bean wrong?

EDIT: after adding one more bean to it this is what I get when I run my program:

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@e949f69: defining beans [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"

Upvotes: 0

Views: 441

Answers (2)

NickJ
NickJ

Reputation: 9579

Certainly remove static modifiers on your fields, as already suggested. Also, if you want 'singletons' modify your 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. You'll still get multiple instances of Generator, but only one per bean.

Upvotes: 2

vcetinick
vcetinick

Reputation: 2017

Based on comments, I can only assume that the Generator class looks something like this

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.

Upvotes: 1

Related Questions