Aravind
Aravind

Reputation: 2198

Autowiring String property through application context

I want to autowire a String bean as below

<bean id="name" class="java.lang.String" autowire="byName">
        <constructor-arg value="Aravind"/>
</bean>
<bean id="employee" class="Employee" autowire="byName"/>

public Class Employee
{
   private String name;
   public void setName(String name)
   {
     this.name=name;
    }
   public String getName()
   {
     return name;
   }
}

When I try to access the name attribute in the employee is null

Employee emp=(Employee)getApplicationContext().getBean("employee");
System.out.println(emp.getName()==null);

It prints true.

Can someone help on this?

Upvotes: 0

Views: 89

Answers (1)

Bart
Bart

Reputation: 17371

You still need to set the property on the Employee somehow.

Setting the name can be done in multiple ways.

XML configuration.

<bean id="employee" class="Employee" autowire="byName">
    <property name="name">
        <ref bean="name" />
    </property>
</bean>

Using @Autowired

public Class Employee {
   @Autowired
   private String name;

   public void setName(String name) {
     this.name=name;
   }

   public String getName() {
     return name;
   }
}

Upvotes: 1

Related Questions