≡ Menu

Repost: Rocket Java: Spring Injection of Other Beans’ Properties

Woot, IRC FTW! Someone today asked a question about Spring that was actually relevant for once.

The problem was that he wanted to inject not a bean, but a bean’s referenced property into another bean.

Put more succintly: He had a bean A, with a property B, and didn’t want to inject A into bean C, but wanted to inject the result of A.getB().

This is actually pretty easily done… as long as you’re on the Spring 3.0 revision. The key is the spring-expression module; it lets us, well, use expressions in our Spring configuration.

So let’s build a sample and show this puppy in action. First, we’ll create our two classes, as referenced above, using Lombok to create our mutators and accessors:

public class A {
   @Getter @Setter String b;

public class C {
   @Getter @Setter String d;
   public void run() { System.out.printf("%s%n", getD()); }

So our goal is to have run() output the value of A.b, even though C has no reference to A.

With spring-expression, the configuration file is really pretty simple. It looks like this:

    <bean id="a" class="sandbox.A">
        <property name="b" value="hello, world"/>
    <bean id="c" class="sandbox.C">
        <property name="d" value="#{a.b}"/>

The expression is the key. “#{a.b}” means to follow the object hierarchy – including bean references, which is where the “a” comes in – and use property b from reference a.

It’s as simple as pi. (Because, after all, pi is just 3.14159… wait. pi is an irrational number. If only I could make pie!)

Incidentally, as a bit of an aside: I used Lombok up there to add mutators and accessors via annotation, which is really convenient; however, if you use it in IDEA, note that the editor in IDEA isn’t able to infer the new methods, so it shows me lots of red. I really dislike warnings (and hints of warnings) in my code, and errors… horrors! (I’m error-phobic.)

But it runs, folks. I promise.

Author’s Note: Yet another repost.

{ 0 comments… add one }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: