tuntun wretee
tuntun wretee

Reputation: 49

Passing reference of bean into another bean

I have a class A which contain the following

class A
{

private HashSet<Long> at = new HashSet<Long>();

and it has a constructor like this

A()
{
//set is being initialsised here 

                this.at.add(new Long(44));
        this.at.add(new Long(34));
        this.at.add(new Long(54));
        this.at.add(new Long(55));


}

Now following is the spring xml bean defined for it ...

<bean id="aa" class="com.abc.A">
        <property name="readPermissionGroup">
      <set>
         <value>03</value>
         <value>13</value>
         <value>54</value>
         <value>55</value>
      </set>
   </property>
    </bean>

Now please advise how can I add the above bean aa into bb as the bean bb contain the complete defination of class A

Upvotes: 2

Views: 1596

Answers (2)

Diptopol Dam
Diptopol Dam

Reputation: 815

You can use @Anotation to inject the bean A. Use @Bean annotation in the class A. @Bean annotation will create bean A.

class B {
    @Autowired
    private A beanA;
    // setter and getter
}

Here is your class A

@Bean
 class A
  {
  private HashSet<Long> at = new HashSet<Long>();
  A()
   {
   //set is being initialsised here 

    this.at.add(new Long(44));
    this.at.add(new Long(34));
    this.at.add(new Long(54));
    this.at.add(new Long(55));
}

Upvotes: 0

erencan
erencan

Reputation: 3763

Define class B into Spring context

<bean id="bb" class="com.abc.B"></bean>

Add an A class referance to class B like

class B
{
    private A beanA;

    //setters getters
}

and inject bean A to bean B in your xml configuration. Modify bean B defination

<bean id="bb" class="com.abc.B">
<property name="beanA" ref="aa" />
</bean>

My suggestion is not to use xml to define and inject beans. It is really old, use annotations instead.

Upvotes: 1

Related Questions