package com.ylchou.testSpring;
public class HelloJava {
private String say;
//setter必须要无参构造函数。没有有参构造函数时,可不写无参构造函数,因为默认有无参构造函数;有有参构造函数时,必须写无参构造函数
//constructor可以无
//总结:无论setter还是constructor,都必须要有构造器(无论有参还是无参,无论默认还是显示地写),
public HelloJava() {
}
public HelloJava(String say) {
super();
this.say = say;
}
public String getSay() {
return say;
}
public void setSay(String say) {
this.say = say;
}
}
<?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-2.5.xsd">
<bean id="HelloJavass" class="com.ylchou.testSpring.HelloJava">
<!--
<property name="say" >
<value>Hello,chousoul!</value>
</property>
-->
<!--
<constructor-arg index="0">
<value>Hello,xyz</value>
</constructor-arg>
-->
<constructor-arg>
<value>Hello,yy!</value>
</constructor-arg>
</bean>
</beans>
package com.ylchou.testSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
// FileSystemXmlApplicationContext fsx = new FileSystemXmlApplicationContext();//有误
// ApplicationContext fsx = new FileSystemXmlApplicationContext("applicationContext.xml");
// ApplicationContext fsx = new ClassPathXmlApplicationContext();//貌似有误
ApplicationContext fsx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloJava helloJava = (HelloJava)fsx.getBean("HelloJavass");
// HelloJava hj = new HelloJava();
// hj.getSay();
System.out.println(helloJava.getSay());
}
}
ApplicationContext fsx = new ClassPathXmlApplicationContext("applicationContext.xml");取得在src目录下的applicationContext.xml
ApplicationContext fsx = new FileSystemXmlApplicationContext("applicationContext.xml");取得在项目目录下的applicationContext.xml