2

Within Spring DI, can you "use" your bean within it's own definition? For example, if I have a bean called getTest1 with an inner bean declared within it, can I pass getTest1 to the constructor of that inner bean?

I'm wondering if I can implement a decorator patter-like solution using Spring DI for a work project but don't have much time to play around with it. Thanks!

2 Answers 2

1

Haven't tested it but I think you need something like this

<bean id="a" class="com.AClass">
   <property name="aProperty" value="y">
   <property name="bean2">
      <bean class="com.BClass">
        <constructor-arg ref="a"/>
      </bean>
   </property>
</bean>

check here for more help on referencing one bean inside another

Sign up to request clarification or add additional context in comments.

1 Comment

The scope of "a" is by default singleton . Hence I don't think a brand new "A" bean will be created.See here for a discussion on this.
1

The decorator pattern can be expressed in the following way using XML:

<bean id="decorated" class="Outer">
    <constructor-arg>
        <bean class="Middle">
            <constructor-arg>
                <bean class="Inner"/>
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>

This is equivalent to the following Java code:

Common decorated = new Outer(new Middle(new Inner()));

Consider Using @Configuration approach to make this more Java-friendly:

@Bean
public Common outer() {
  return new Outer(middle());
}

@Bean
public Common middle() {
  return new Middle(inner());
}

@Bean
public Common inner() {
  return new Inner();
}

1 Comment

This looks like it would also work for what I'm doing but I was looking for a way to shortcut and let Spring make my concrete class to be decorated instead of coding one. Thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.