spring学习之控制反转(IOC)

01 控制反转(IOC)

⼯⼚就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的⽅式发⽣了改变。 Spring就是 我们的⼯⼚⻆⾊

以前: 我们在获取对象时,都是采⽤new的⽅式。是主动的。

 

现在: 我们获取对象时,同时跟⼯⼚要,有⼯⼚为我们查找或者创建对象。是被动的。

 

这种被动接收的⽅式获取对象的思想就是 ==》控制反转,它是spring框架的核⼼之⼀。

1.1 IOC的作⽤:使⽤spring的IOC解决程序耦合

明确IOC的作⽤: 削减计算机程序的耦合(解除我们代码中的依赖关系)。

1.2 实现IOC方式:基于XML配置的IOC、基于注解的IOC

 

02 基于XML配置的IOC

2.1 pom⽂件引⼊依赖

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>5.2.1.RELEASE</version>
</dependency>

2.2 创建业务层接⼝和实现类

  • 接口
public interface IAccountService {
 /**
 * 保存账户(此处只是模拟,并不是真的要保存)
 */
 void saveAccount();
}
  • 实现类
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = new AccountDaoImpl();//此处的依赖关系有待解决
    public void saveAccount() {
       accountDao.saveAccount();
    }
}

2.3 基于XML的配置

  • 在类的根路径下创建⼀个任意名称的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标签:⽤于配置让spring创建对象,并且存⼊ioc容器之中 id属性:对象的唯⼀标识。
class属性:指定要创建对象的全限定类名 -->
 <!-- 配置service -->
 <bean id="accountService" class="com.dgut.Service.impl.AccountServiceImpl"></bean>
 <!-- 配置dao -->
 <bean id="accountDao" class="com.dgut.dao.impl.AccountDaoImpl"></bean>
</beans>

 bean标签:⽤于配置让spring创建对象,并且存⼊ioc容器之中

     - id属性:对象的唯⼀标识。
     - class属性:指定要创建对象的全限定类名 (不能是接口,是接口的实现类

<bean id="accountService" class="com.dgut.Service.impl.AccountServiceImpl"></bean> 相当是以前的AccountServiceImpl accountService=new AccountServiceImpl();

  • 编写测试类
public class SpringTest {
 public static void main(String[] args) {
 ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
 //2.根据bean的id获取对象
 IAccountService aService = (IAccountService)ac.getBean("accountService");
 System.out.println(aService);
 IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
 System.out.println(aDao);
 }
}

ClassPathXmlApplicationContext("beans.xml");获取上下文(即spring容器)

ac.getBean("accountService");根据bean的id获取对象

3.4 ApplicationContext 类图

ClassPathXmlApplicationContext: 它是从类的根路径下加载配置⽂件 推荐使⽤这种

FileSystemXmlApplicationContext: 它是从磁盘路径上加载配置⽂件,配置⽂件可以在磁盘的任意位置。

AnnotationConfigApplicationContext: 当我们使⽤注解配置容器对象时,需要使⽤此类来创建spring 容器。它⽤来读取注解

3.5 IOC中bean标签和管理对象

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值