淺談spring框架--IOC
阿新 • • 發佈:2018-12-21
Spring框架中主要以IOC(Inversion of Control)控制反轉 和 AOP(Aspect Oriented Programming)面向切面程式設計為核心。
IOC(Inversion Of Control)控制反轉,是面向物件程式設計的一個重要法則,用於削減計算機程式間的耦合問題。控制反轉中分為兩種型別,一種是DI(Dependency Injection)依賴注入;另外一種是DL(Dependency Lookup)依賴查詢。
使用IOC控制反轉有三種操作方式:1.基於xml配置 2.xml配置+註解配置 3.純註解配置
下面演示一下基於xml配置操作方式(注:以下操作是基於三層架構演示
1.基於xml配置檔案
/** * 客戶dao介面 */ public interface CustomerDao { /** * 儲存客戶 */ void saveCustomer(); } /** * 客戶dao實現類 */ public class CustomerDaoImpl implements CustomerDao { /** * 儲存客戶 */ public void saveCustomer() { System.out.println("儲存客戶。"); } } /** * 客戶service介面 */ public interface CustomerService { /** * 儲存客戶 */ void saveCustomer(); } /** * 客戶service實現類 */ public class CustomerServiceimpl implements CustomerService { // 客戶dao private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } /** * 儲存客戶 */ public void saveCustomer() { customerDao.saveCustomer(); } }
配置pom.xml檔案,加入ioc依賴包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <properties> <!--spring版本--> <spring.version>5.0.2.RELEASE</spring.version> </properties> <dependencies> <!--spring ioc依賴包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies> </project>
編寫bean.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">
<!--配置客戶service-->
<bean id="customerService" class="cn.itheima.service.impl.CustomerServiceimpl">
<!--注入客戶dao-->
<property name="customerDao" ref="customerDao"></property>
</bean>
<!--配置客戶dao-->
<bean id="customerDao" class="cn.itheima.dao.impl.CustomerDaoImpl"></bean>
</beans>
編寫表現層controller
/**
* 客戶表現層物件
*/
public class CustomerController {
public static void main(String[] args) {
// 1.載入spring配置檔案,建立spring容器
/**
* classpath:==》表示從類的根路徑下載入配置檔案,可以加也可以不加。
* spring框架建議我們加上。
*/
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
// 2.從spring容器中,獲取客戶service物件
CustomerService customerService = (CustomerService) context.getBean("customerService");
// 3.儲存客戶
customerService.saveCustomer();
}
}
測試的效果圖: