控制反轉(IOC)是Spring架構的核心内容,本篇内容将利用Spring的IOC,來輸出Hello,Spring。
為什麼需要用IOC
據說,IOC能夠極大地友善開發。
在使用IOC之前,先看看如何用傳統的實作類的方式,輸出Hello,Spring。
傳統方式:
1.先寫一個UserDao接口
public interface UserDao {
public void getUser();
}
2.再去寫Dao的實作類
public class UserDaoImpl implements UserDao {
@Override
public void getUser() {
System.out.println("Hello,Spring");
}
}
3.然後去寫UserService的接口
public interface UserService {
public void getUser();
}
4.最後寫Service的實作類
public class UserServiceImpl implements UserService {
private UserDaoImpl userDao = new UserDaoImpl();
@Override
public void getUser() {
userDao.getUser();
}
}
5.測試一下
public class UserServiceImpl implements UserService {
private UserDaoImpl userDao = new UserDaoImpl();
@Override
public void getUser() {
userDao.getUser();
}
}
輸出結果:
檔案結構:
但是,如果把Userdao的實作類增加一個,service實作類也需要修改,如果多了之後,修改起來就非常麻煩。
IOC概述
在上面的例子中,新的需求需要同時改兩個檔案,代碼的耦合度過高。
而Spring的IOC就相當于一個容器,将各部分代碼分離開來,通過一個容器連接配接,極大降低耦合度。
IOC的使用
導入Jar包
通過Maven,可以自動下載下傳依賴。
在pom.xml檔案中添加:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
</dependencies>
打開Maven,點選重新整理,它就會自動安裝。
安裝好後,可以看到下面的一些依賴:
代碼編寫
1.編寫一個Hello實體類
package com.kuang.polo;
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello,"+ name );
}
}
2.在resources檔案夾中建立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就是java對象 , 由Spring建立和管理-->
<bean id="hello" class="com.kuang.polo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
通過< bean id=“hello” class=“com.kuang.polo.Hello”>,就建立了hello這個對象,下面的property通過value對其進行注入指派。
3.進行測試
import com.kuang.polo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//解析beans.xml檔案 , 生成管理相應的Bean對象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean : 參數即為spring配置檔案中bean的id .
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
}
4.結果檢視
5.檔案結構
IOC總結
通過比較上面兩種方法來輸出Hello,Spring,可以發現後者的方式比前者簡單很多。并且,後者通過xml檔案實作了對象的建立,不需要修改具體的java代碼,友善管理。