初識spring,IOC
bean是spring中最核心的東西,因爲spring就像是個大水桶,而bean就像是容器中的水,水桶脫離了水便沒什麼用處了,那麼我們先定義個bean:
public class UserService {
public void sing(){
System.out.println("唱歌------");
}
}
很普通,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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--id用戶區分bean的標識-->
<bean id="userService" class="com.adwo.UserService" ></bean>
</beans>
在上面的配置文件中,我們看到了bean的聲明方式,儘管spring中bean的元素定義着N種屬性來支撐我們業務的各種應用,但是我們只要聲明成這樣,基本上就已經滿足我們的大多數應用了,接下來我們編寫測試代碼:
public class UserTest {
public static void main(String[] args) {
String path="beans.xml";
//加載類路徑下的配置文件
ApplicationContext app = new ClassPathXmlApplicationContext(path);
UserService userService = (UserService) app.getBean("userService");//根據bean的id獲取實體
userService.sing();
}
打印如下:
唱歌------
好了,一個完整的spring入門實例到這裏就結束了,那我們來好好的分析一下上面的測試代碼的功能,來探索上面的測試代碼中spring究竟幫助我們完成了什麼工作?這段測試代碼完成的功能就一下幾點:
1、讀取配置文件beans.xml。
2、根據beans.xml中的配置找到對應的類的配置,並實例化。
3、調用實例化後的實例。
其實這就是spring的IOC,即 Inverse of Control控制反轉,就是將原本在程序中創建UserService對象的控制權,交由spring框架管理,簡單的說,就是創建UserService 對象的控制權被反轉到了spring框架。
傳統的方式是:
public static void main(String[] args) {
//傳統自己創建new
UserServiceservice = new UserService();
service.sing();
}