Reputation: 3359
I have a POJO with a field message
:
package com.packt.lifecycle;
public class HelloWorld {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
In my app context XML I have 2 bean definitions:
<bean id="helloWorld" class="com.packt.lifecycle.HelloWorld" autowire="byName">
</bean>
<bean name="message" class="java.lang.String" >
<constructor-arg value="auto wired1" />
</bean>
However, the autowiring by name for some reason doesn't work. The following code displays null:
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld world = (HelloWorld) context.getBean("helloWorld");
System.out.println(world.getMessage());
Upvotes: 0
Views: 308
Reputation: 1
Autowire doesn't work because the property is not configured in Spring. Put the annotation on the field or method to let the Spring know that this property needs autowiring.
@Component
public class HelloWorld {
private String message;
public String getMessage() {
return message;
}
@Autowired
public void setMessage(String message) {
System.out.println(message);
this.message = message;
}
}
To make annotations work you need something like
<!--<context:annotation-config/>-->
<context:component-scan base-package="com.packt.lifecycle"/>
Upvotes: 0
Reputation: 20783
You can not autowire strings like that. Check out the exceptions for auto-wiring.
I think auto-wiring of constant primitives are discouraged so that they are created like property values - that will force you to externalize your constants to a property file which sounds more appropriate.
Rather define your message in a properties file as :
message.key=Hello World
Then load your properties with a PropertyConfigurer
and then autowire constant properties as :
@Value("${message.key}")
private String message;
or provide a default value (hard coded) as
@Value("${useDefault:Hello World}")
private String message;
Upvotes: 2
Reputation: 4999
Just add your property within your bean definition:
<bean id="helloWorld" class="com.packt.lifecycle.HelloWorld" autowire="byName">
<property name="message" value="auto wired1" />
</bean>
Upvotes: -1