一、創建工程
1.創建Spring項目
2.工程自動下載Spring框架所需要的的jar包
https://repo.spring.io/libs-release-local/org/springframework/spring/5.2.3.RELEASE/
如果遇到網絡問題,可以從這裏下載後,配置進工程
二、測試
helloSpring
public class helloSpring {
private String name;
public void setName(String name){
this.name = name;
}
public void sayHello(){
System.out.println("hello"+name);
}
}
Main
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
//傳統創建方法
helloSpring hello = new helloSpring();
hello.setName(" old method");
hello.sayHello();
//採用Spring框架
//創建Spring IOC容器對象 Inversion of Control 控制反轉
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//從ioc容器獲取bean對象
helloSpring HelloSpring = (helloSpring)context.getBean("helloSpring");
HelloSpring.sayHello();
}
}
Spring-config.xml
輸出結果
總結:
創建實例對象以及設置對象的屬性,也就是說我們可以把對象的創建和管理工作交給Spring去完成,不需要自己去new對象,也不要去設置對象的屬性,只要寫好Spring的配置文件,Spring就可以幫我們去做,當我們需要對象的時候,直接去找Spring去要就行。