- 新建一个普通的java工程
- 将spring jar包引用到工程中
- 在src下新建目录 com.springstudy
- 在目录下新建java项目
(1)HelloSpring.java
package com.springstudy;
public class HelloSpring {
private String message;
public void getMessage() {
System.out.println("Your Message is " + message);
}
public void setMessage(String message) {
this.message = message;
}
}
(2) MainApp.java
package com.springstudy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("D:\\workspace-springstudy\\HelloSpring\\src\\Beans.xml");
HelloSpring obj = (HelloSpring) context.getBean("hellospring");
obj.getMessage();
}
}
- 在src下新建Beans.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="hellospring" class="com.springstudy.HelloSpring">
<property name="message" value="Hello Spring!!!"/>
</bean>
</beans>
运行结果
注 :ClassPathXmlApplicationContext与FileSystemXmlApplicationContext区别:
ClassPathXmlApplicationContext后加相对路径
FileSystemXmlApplicationContext后加绝对路径