3、HelloSpring
思考
- Hello 對象是誰創建的 ? 【 hello 對象是由Spring創建的 】
- Hello 對象的屬性是怎么設置的 ? 【hello 對象的屬性是由Spring容器設置的 】
這個過程就叫控制反轉 :
- 控制 : 誰來控制對象的創建 , 傳統應用程序的對象是由程序本身控制創建的 , 使用Spring后 , 對象是由Spring來創建的
- 反轉 : 程序本身不創建對象 , 而變成被動的接收對象 .
依賴注入 : 就是利用set方法來進行注入的.
IOC是一種編程思想,由主動的編程變成被動的接收
可以通過newClassPathXmlApplicationContext去瀏覽一下底層源碼 .
修改案例一
我們在案例一中, 新增一個Spring配置文件beans.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="MysqlImpl" class="com.kuang.dao.impl.UserDaoMySqlImpl"/>
<bean id="OracleImpl" class="com.kuang.dao.impl.UserDaoOracleImpl"/>
<bean id="ServiceImpl" class="com.kuang.service.impl.UserServiceImpl">
<!--注意: 這里的name並不是屬性 , 而是set方法后面的那部分 , 首字母小寫-->
<!--引用另外一個bean , 不是用value 而是用 ref-->
<property name="userDao" ref="OracleImpl"/>
</bean>
</beans>
測試!
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
serviceImpl.getUser();
}
OK , 到了現在 , 我們徹底不用再程序中去改動了 , 要實現不同的操作 , 只需要在xml配置文件中進行修改 , 所謂的IoC,一句話搞定 : 對象由Spring 來創建 , 管理 , 裝配 !
4、IOC創建對象的方式
-
使用無參構造創建對象,默認!
-
假設我們要使用有參構造創建對象
-
下標賦值
<!--第一種,下標賦值--> <bean id="user" class="com.rui.pojo.User"> <constructor-arg index="0" value="狂神說Java"/> </bean>
-
通過類型賦值
<!--第二種方式:通過類型創建,不建議使用--> <bean id="user" class="com.rui.pojo.User"> <constructor-arg type="java.lang.String" value="尹銳"/> </bean>
-
通過屬性名賦值
<!--第三種,直接通過參數名實現賦值--> <bean id="user" class="com.rui.pojo.User"> <constructor-arg name="name" value="尹銳"/> </bean>
-
總結:在配置文件加載的時候,容器中管理的對象就已經初始化了!