Question

I am trying to achieve lookup method injection using a simple example. But, seems to fail in getting the bean injected via the method.

I have a simple bean namely; DemoBean as below:

public class DemoBean {

    private String message;

    public DemoBean() {

    }

    public DemoBean(String message) {
        this.message = message;
    }

    // Getter and Setter methods

    @Override
    public String toString() {
        return "DemoBean{" +
                "message='" + message + '\'' +
                '}';
    }
}

I am trying to inject DemoBean into another bean namely; PropertyBean:

public abstract class PropertyBean {

    private DemoBean bean;
    private String message;
    // other members...

    public PropertyBean(String message) {
        this.message = message;
    }

    // Getter and Setter methods...

    // Method for lookup injection
    protected abstract DemoBean createBean();

    @Override
    public String toString() {
        return "PropertyBean{" +
                "bean=" + bean.toString() +
                ", message='" + message + '\'' +
                ", number=" + number +
                '}';
    }
}

Noe, there is my beans configuration:

<bean id="demobean" class="aro.discoverspring.beans.DemoBean" scope="prototype">
<property name="message" value="The Default Message!!!" />
</bean>

<bean id="propertybean" class="aro.discoverspring.beans.PropertyBean">
<constructor-arg name="message" value="A message in PropertyBean"/>
<lookup-method name="createBean" bean="demobean" />
</bean>

When try to create an instance of PropertyBean. I am able to do so. But when I do the following.. I get null pointer exception on the DemoBean property (Because the bean is not getting injected!!)

PropertyBean pb = (PropertyBean) ctx.getBean("propertybean");       
System.out.println(pb.toString());

What am I doing wrong? Did I miss anything or am I overlooking something silly there!? Spring 3.0 reference (section 3.4.6.1) seems to be doing the same.

Was it helpful?

Solution

bean property shouldn't be injected. As I understand spring implements createBean method for you, so when you call pb.createBean() it should return instance of DemoBean. But you don't assign anything to bean property in ProperyBean so there is no way for it to be not null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top