1、IOC推導
public class UserServiceImplimplements UserService{
? ? ?//第一種,直接new對象,每次新增都需要修改源代碼
? ? //private UserDao userDao = new UserMysqlDaoImpl();
? ? //private UserDao userDao = new UserDaoImpl();
? ? //第二種,set動態(tài)注入,不用修改源代碼,注入的時候修改
? ? private? UserDaouserDao;
? ? public void setUserDao(UserDao userDao) {this.userDao = userDao;}
? ? public void getUser(){userDao.getUser(); }
}
public class MyTest {
public static void main(String[] args) {
? ? ? ? UserServiceImpl service =new UserServiceImpl();
? ? ? ? //service.setUserDao(new UserMysqlDaoImpl());
? ? ? ? service.setUserDao(new UserOracleDaoImpl());
? ? ? ? service.getUser();
? ? }
}
根據(jù)用戶需求修改源代碼奉瘤,代碼量大的話,修改工作量大煮甥。使用set接口實現(xiàn)盗温,革命性變化。
之前成肘,程序是主動的卖局,控制權(quán)在程序猿手上。使用set之后双霍,程序不再具有主動性砚偶,而是被動接收對象。
這種思想從根本上解決問題洒闸,程序猿不用在管理對象的創(chuàng)建了染坯,系統(tǒng)耦合性降低,專注業(yè)務(wù)實現(xiàn)丘逸。
2单鹿、IOC本質(zhì)
xml方式配置Bean,Bean的定義和實現(xiàn)分離深纲,而注解方式兩者合一仲锄,Bean的定義信息直接以注解的形式定義在實現(xiàn)類中從而達到零配置的目的劲妙。
控制反轉(zhuǎn)是一種通過描述(xml或注解)并通過第三方生產(chǎn)或獲取特定對象的方式。Spring中實現(xiàn)控制反轉(zhuǎn)的是IOC容器儒喊,其實現(xiàn)方式是依賴注入(DI)镣奋。
3、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">
? ? <!--spring創(chuàng)建對象Hello hello = new Hello();
? ? id 變量名? ? class new的對象? ? property 給對象屬性設(shè)置值-->
? ? <bean id="hello" class="com.kuang.pojo.Hello">
? ? ? <property name="name" value="Spring">
? ? </bean>
? ? <!--spring創(chuàng)建對象 ref 引用的對象 value 基本類型-->
? ? <bean id="mysqlDaoImpl" class="com.kuang.dao.UserMysqlDaoImpl"/>
? ? <bean id="oracleDaoImpl" class="com.kuang.dao.UserOracleDaoImpl"/>
? ? <bean id="userService" class="com.kuang.service.UserServiceImpl">
? ? ? ? ?<property name="userDao" ref="mysqlDaoImpl">
? ? ?</bean>
</beans>
spring創(chuàng)建對象怀愧,對象屬性在spring容器中設(shè)置唆途,這個過程叫做控制反轉(zhuǎn)。
控制指誰來控制對象創(chuàng)建掸驱,傳統(tǒng)對象由程序本身創(chuàng)建,使用spring后由spring創(chuàng)建没佑。
反轉(zhuǎn)指程序本身不創(chuàng)建對象毕贼,變成被動接收對象。
依賴注入就是set方法進行注入的蛤奢。
調(diào)用
//spring上下文對象
ApplicationContext applicationContext? =new ClassPathXmlApplicationContext("beans.xml");
//spring中獲取對象
Hello hello = (Hello) applicationContext.getBean("hello");
System.out.println(hello);
IOC就是對象由spring創(chuàng)建鬼癣、管理、裝配
以上參考啤贩,kuangshen視頻待秃。