我有一个简单的名为HelloWorld
的spring项目,并尝试从applicationContext.xml
文件加载两个属性,但属性不会在相应的setter中设置。
的pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
主要方法:
public class MyApp {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
TrackCoach trackCoach = context.getBean("myCoach", TrackCoach.class);
trackCoach.getDailyWorkout();
System.out.println(trackCoach.getName());
System.out.println(trackCoach.getFamily());
}
}
TrackCoach.java
public class TrackCoach {
private String name;
private String family;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("name is set");
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
System.out.println("family is set");
this.family = family;
}
public void getDailyWorkout() {
System.out.println("track coach!");
}
}
的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="myCoach" class="TrackCoach">
<property name="name" value="Jhon"/>
<property name="family" value="Goo"/>
</bean>
</beans>
输出结果为:
track coach!
null
null
答案 0 :(得分:0)
在定义bean时应该给出完整的类名,例如类com.test包中存在TrackCoach然后它就像 com.test.TrackCoach
<bean id="myCoach" class="com.test.TrackCoach">
答案 1 :(得分:0)
我在applicationContext.xml文件中看到了许多问题:
您发布的pom.xml具有两次相同的依赖关系。要运行spring基本示例,您需要spring-core
jar以及spring-context
jar。
定义spring-context名称空间。如果需要,您可以指向特定版本的xsd。虽然截至目前您还没有使用任何与上下文相关的标签,但对于大多数弹簧基本情况,您将需要它。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
您应该使用完全限定的类名来标识该类。使用包来分类。
<bean id="myCoach" class="com.beans.TrackCoach">
<property name="name" value="Jhon"/>
<property name="family" value="Goo"/>
</bean>