Spring HelloWorld
使用Spring:
1.創建一個java工程
2.添加jar包
3.創建一個類(Helloworld.java)
package com.tuxianchao.spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorld {
private String name;
public HelloWorld() {
System.out.println("HelloWorld's Constructor...");
}
public void setName(String name) {
System.out.println("HelloWorld's setName..");
this.name = name;
}
public void hello() {
System.out.println("hello:" + name);
}
public static void main(String[] args) {
// 沒有使用Spring的時候:
// // 1.創建一個helloworld對象
// helloWorld helloWorld = new helloWorld();
// // 2.爲對象的屬性賦值
// helloWorld.setName("spring");
// // 3.使用對象的方法
// helloWorld.hello();
// 使用spring
// 1.創建spring的IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.從容器中獲取bean實例
HelloWorld helloWorld = (com.tuxianchao.spring.beans.HelloWorld) ctx.getBean("helloworld");
// HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
// 3.使用對象方法
helloWorld.hello();
}
}
4.在類路徑下建立spring的配置文件(ApplicationContext.xml)
5.在配置文件中配置bean
<?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.xsd">
<!-- 配置bean -->
<bean id="helloworld" class="com.tuxianchao.spring.beans.HelloWorld">
<property name="name" value="Spring"></property>
</bean>
</beans>