作者jtorngl (透)
站内java
标题[问题] 请问Spring的constructor injection
时间Tue Jul 27 16:49:54 2010
最近在接触Spring,从IoC的设定开始看,并练习一个范例
HelloBean.java
public class HelloBean {
private String helloWord;
public HelloBean() {
}
public HelloBean(String helloWorld) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
}
SpringDemo.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class SpringDemo {
public static void main(String[] args) {
Resource rs = new FileSystemResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
beans-config.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:aop="
http://www.springframework.org/schema/aop"
xmlns:tx="
http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- type 2 IoC -> setter injection -->
<!--
<bean id="helloBean" class="HelloBean">
<property name="helloWord" value="hello, Tony!"></property>
</bean>
-->
<!-- type 3 IoC -> constructor injection -->
<bean id="helloBean" class="HelloBean">
<constructor-arg>
<value>hello, May!</value>
</constructor-arg>
</bean>
</beans>
编译好的class档和beans-config.xml放在同一个目录(classes)下
D:\SpringDemo\Demo_01\classes>java -classpath .;..\lib\* SpringDemo
2010/7/27 下午 04:30:45
org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
资讯: Loading XML bean definitions from file [D:\SpringDemo\Demo_01\classes\beans-config.xml]
null
改成setter injection时,是有把hello, Tony!注入helloWorld
但是constructor injection时,helloWorld的值为null
请问问题是在什麽地方呢
另请问为什麽执行时,都要加入classes的路径?
HelloBean和SpringDemo的class档案在同一个package下了
D:\SpringDemo\Demo_01\classes>java -classpath ..\lib\* SpringDemo -> ×
D:\SpringDemo\Demo_01\classes>java -classpath .;..\lib\* SpringDemo -> ○
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 219.87.128.98
1F:推 dwi2:1.因为你的两个bean的id都叫helloBean,第2个bean改名字跑看看 07/27 17:53
2F:→ jtorngl:我第一个bean注解了 07/27 18:59
3F:推 dwi2:恩....HelloBean的constructor里面拼字有点怪怪的 07/27 21:35