Spring——HelloSpring第一個專案
阿新 • • 發佈:2020-09-01
首先建立實體類
package com.yl.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
在recourses目錄下建立一個spring配置檔案:beans.xml
測試:
public static void main(String[] args) {
//獲取spring的上下文物件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我們的物件現在都在spring中管理了,我們要使用,直接去裡面取出來就可以
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
到目前為止,已經徹底不用在程式中改動了,要實現不同的操作,只需要在xml配置檔案中進行修改,物件由Spring來建立 管理和裝配
對應改造上一個程式:
-
增加配置檔案
-
測試:
public static void main(String[] args) {
//獲取ApplicationContext,拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//需要什麼就直接get什麼
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
控制
誰來控制物件的建立,傳統應用程式的物件是由程式本身控制建立的,使用Spring後,物件是由Spring來建立的
反轉
程式本身不建立物件,而被動的接收物件
依賴注入
就是利用set方法來進行注入的
IOC是一種程式設計思想,由主動的程式設計變為被動的接受