[問題] 請問Spring的constructor injection
最近在接觸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
" rel="nofollow">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
推
07/27 17:53, , 1F
07/27 17:53, 1F
→
07/27 18:59, , 2F
07/27 18:59, 2F
推
07/27 21:35, , 3F
07/27 21:35, 3F