Ioc控制反转

spring – IOC

IOC是一个概念是一种思想 , 其实现的方式多种多样 ,当前比较流行的实现方式是依赖注入

依赖在的意思是类A中含有B的实例,在A中调用B的方法完成功能,即A对B有依赖 ,

1、控制反转
就是将对象的控制权有类交给我们我们的spring容器来管理, 有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 http://www.springframework.org/schema/beans/spring-beans.xsd">
		<bean   id="SomeService"  class = "com.baidu.service.SomeServiceImpl" />
</beans>
<!--
<bean . > 用于定义一个实例对象 一个实例对象对应一个bean标签
其中id 是该属性Bean的唯一标识  
		class 指定该Bean所属的类   ,  注意是类  不是接口
【id】 细心观察就发现  id 其实就是这个接口实现类对应的接口
-->

下面通过一个程序
简单看一下spring管理对象创建对象

applicationContext.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 id="someService2" class="com.bjpowernode.service.impl.SomeServiceImpl"></bean>

</beans>

定义一个测试类

public class MyApplication {
    
    public static void main(String[] args) {
        //定义变量
        String config = "applicationContext.xml";

        //创建接口实现类,根据配置文件的位置,选择applicationContext接口实现类
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);

        //3.从容器中根据id的名称获取对象
        SomeService service = (SomeService) ctx.getBean("someService2");

        //调用对象的业务方法
        service.doSome();
    }
}

接口和对应的接口实现类

public class SomeServiceImpl implements SomeService {
    @Override
    public void doSome() {
        System.out.println("执行了Some方法");
    }
}
------------------------------------------------------
public interface SomeServicee(){ 
    	void doSome();
}

通过上面这个例子就可以看出spring来创建对象 管理对象。IOC控制反转将对象的控制权有类文件 交给spring容器来管理

2.容器中Bean的作用域

  1. singleton 单例模式 在整个spring容器中 , 使用了singleton 属性的 就是 单例模式,创建的对象都是同一个对象
  2. prototype 原型模式 ,与单例相反 , 每次得到的都是一个新的对象
  3. request 对于每次http请求 , 所创建的对象都是一个新的实例对象
  4. session , 对于每个不同的httpSession , 所创建的对象都不是同一个实例对象

后面谈谈使用注解的方式给对象的属性赋值,AOP面向切面编程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值