spring第一個(gè)程序HelloWorld
1新建java項(xiàng)目
2導(dǎo)入一下jar

image.png
3新建HelloWorld
package chen;
public class HelloWorld {
private String name;
public void hello() {
System.out.print(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4配置bean.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.xsd">
<bean id="hello" class="chen.HelloWorld">
<property name="name" value="你好 Spring"></property>
</bean>
</beans>
5程序入口
package chen;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// 1.創(chuàng)建ioc容器對象
//ApplicationContext代表ioc容器
//ClassPathXmlApplicationContext:是ApplicationContext的實(shí)現(xiàn)類 從類路徑下加載配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
// 2.從ioc容器中獲取bean實(shí)例
//利用id獲取實(shí)例
//HelloWorld hWorld = (HelloWorld) ctx.getBean("hello");
//利用類型獲取實(shí)例 但類型唯一
HelloWorld hWorld = ctx.getBean(HelloWorld.class);
// 3.調(diào)用方法
hWorld.hello();
}
}
項(xiàng)目結(jié)構(gòu)如下:

image.png
我們的第一個(gè)spring 程序就完成了
- ApplicationContext代表ioc容器
- ClassPathXmlApplicationContext:是ApplicationContext的實(shí)現(xiàn)類 從類路徑下加載配置文件
總結(jié):
- 配置spring bean配置文件
- 創(chuàng)建ioc容器對象
- 從ioc容器中獲取bean實(shí)例
- 調(diào)用方法
下一篇 spring學(xué)習(xí)3