我是Spring框架的新手。我正在努力研究Autowired
概念,但我的输出结果不正确。我使用了波纹管代码。我不知道我错在哪里。任何人都可以帮我解决这个问题吗?如何在春季使用autowire概念?
Employee.java:
package com.autowire;
public class employee {
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public void show()
{
System.out.println("hai my country is:"+country);
System.out.println("hai my name is"+name);
}
}
main.java:
package com.autowire;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;;
public class main {
public static void main(String args[]){
ApplicationContext context=new ClassPathXmlApplicationContext("config/applicationcontext.xml");
employee emp=(employee) context.getBean("b1");
emp.show();
}
}
的applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="b1" class="com.autowire.employee" autowire="byName">
</bean>
<bean id="name" class="com.autowire.checking">
<property name="id" value="12"></property>
<property name="name1" value="yes"></property>
</bean>
<bean id="id" class="com.autowire.checking">
<property name="id" value="12"></property>
<property name="name1" value="yes"></property>
</bean>
</beans>
检查ing.java
package com.autowire;
public class checking {
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String name1;
private int id;
}
输出: 海我的国家是:空海 我的名字ISNULL
对于这种一般性问题,请参考到Spring手册http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s11.html –