在进行IoC操作的时候,要清楚的了解到控制反转的原理。而在代码中去使用,是为什么干什么?是为了降低耦合性,那如何去降低耦合性呢?其实如果过多的去自己新建对象,那么类与类之间的耦合性就会变强,那么IoC解决的就是让spring去帮我们新建对象,而我们只要通过xml/注解的方式去告诉spring,我们需要什么对象。
案例一:无DI的Ioc操作(XML)
首先我们先用在上一篇的案例的代码,我们稍微修改一下,因为避免有人没有看,我还是将代码贴出来。
新建IAccountDao接口
package com.dao;
//账户的持久层接口
public interface IAccountDao {
//模拟保存账户
void saveAccount();
}
新建IAccountDao接口实现类
package com.dao.impl;
import com.dao.IAccountDao;
//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存成功");
}
}
新建IAccountService接口
package com.service;
//账户业务层的接口
public interface IAccountService {
//模拟保存账户
void saveAccount();
}
新建IAccountService接口实现类
package com.service.impl;
import com.dao.IAccountDao;
import com.dao.impl.AccountDaoImpl;
import com.service.IAccountService;
//账户的业务层实现类
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = new AccountDaoImpl();
public AccountServiceImpl(){
System.out.println("对象创建成功");
}
public void saveAccount() {
accountDao.saveAccount();
}
}
新建bean.xml配置文件
注意,xml里的约束需要你自己去找,进入spring.io网站中,按ctrl+f在其中输入xmlns,显示的约束即是我们需要的:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
然后将需要创建的对象通过xml来告诉spring:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--把对象的创建交给spring来管理-->
<bean id="accountService" class="com.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl"></bean>
</beans>
在这里,我们需要创建dao层的对象去操作方法,而也需要sevice层的对象去调用dao层对象。所以我们需要创建两个实现类的对象,以上的配置即可让spring自动创建。
测试类
package com.ui;
import com.dao.IAccountDao;
import com.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//模拟一个表现层,用于调用业务层
//核心容器的两个接口引发出的问题
//ApplicationContext:(单例对象适用) 实际开发中采用此接口
// 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读完配置文件马上就创建配置文件中配置的对象
//BeanFactory:(多例对象适用)
// 它在构建核心容器时,创建对象才去的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象
public class Client {
public static void main(String[] args) {
//获取spring容器的Ioc的核心容器,并根据id获取对象
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\0hasee\\Desktop\\bean.xml");