I am messing around and trying out some sample spring code. In this instance i am trying to create a string and use it inside another bean. the other bean sets the string in a class and then when i call that class hopefully it should print out the message. however, i get an error message. Please could someone suggest what might be wrong here?
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("MyConfig.xml");
SetterMessage message = (SetterMessage) applicationContext.getBean("setStringFromBean");
System.out.println(message.getMessage());
}
public class SetterMessage {
private String message = null;
/**
* Gets message.
*/
public String getMessage() {
return message;
}
/**
* Sets message.
*/
public void setMessage(String message) {
this.message = message;
}
}
<bean id="createString" class="java.lang.String">
<constructor-arg value="Hello from a bean"</constructor-arg>
</bean>
<bean id="setStringFromBean" class="SetterMessage">
<property name="message" ref="createString" />
</bean>
the error is
Oct 23, 2012 8:36:58 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4447393f: startup date [Tue Oct 23 20:36:58 BST 2012]; root of context hierarchy Oct 23, 2012 8:36:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [MyConfig.xml] Oct 23, 2012 8:36:58 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@643ae941: defining beans [defaultMessage,constructorBean,setterMessage]; root of factory hierarchy Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'setStringFromBean' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:549) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1106) at Main.main(Main.java:13)