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();
}
}
测试的效果图: