Spring基础之IOC

 一、ioc是什么

  1、Spring是什么

      spring是以ioc和aop为核心,能整合第三方框架和类库的企业级应用开源框架。

  2、程序的耦合问题

   例子:Driver类必须存在,编译才通过,JdbcDemo依赖Driver,这种类之间或方法之间的依赖关系就称为耦合。注册驱动改为根据类名反射创建对象,Driver类不存在,编译时也能通过,降低程序间的依赖称为解耦。实际开发中,要编译期不依赖,运行时才依赖。

public class JdbcDemo {
    public static void main(String[] args) throws  Exception{
        //1.注册驱动
        // DriverManager.registerDriver(new com.mysql.jdbc.Driver());
     Class.forName("com.mysql.jdbc.Driver");
//2.获取连接//3.获取操作数据库的预处理对象//4.执行SQL,得到结果集//5.遍历结果集//6.释放资源 } }

  

  3、工厂模式解耦

   使用配置文件来配置controller,service,dao三层对象的全限定类名,创建一个类读取配置文件,创建和获取三层对象,这个类就是工厂。使用Map来存放创建的对象,这个Map称为容器。使用工厂模式,获取对象的方式由主动new对象变为被动的由工厂提供,工厂去容器查找或创建。这种被动的获取对象的方式就是控制反转。其作用就是降低程序耦合度。

public class BeanFactory {
    // 1、定义Properties对象
    private static Properties pros;
    // 2、定义保存对象的容器
    private static Map<String, Object> beans;
    // 3、使用静态代码块为Properties赋值
    static {
        try {
            // 4、读取配置文件
            pros = new Properties();
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            pros.load(in);
            // 5、实例化容器    
            beans = new HashMap<String, Object>();
            // 6、取出配置文件所有key(三层对象的类名)
            Enumeration keys = pros.keys();
            // 7、遍历枚举
            while (keys.hasMoreElements()) {
                String key = keys.nextElement().toString();
                // 8、根据key取出全限定类名
                String beansPath = pros.getProperty(key);
                // 9、反射创建对象
                Object value = Class.forName(beansPath).newInstance();
                // 10、保存key(id)和value(对象)到容器
                beans.put(key, value);        
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
    }
    
    /**
     * 根据bean的名称获取对象
     */
    public static Object getBean(String beanName){
        return beans.get(beanName);
    }
}

  4、ioc是什么 

   ioc(inversion of control),意思是控制反转,将创建对象的权限交给框架,获取对象的方式由主动变为被动。spring就是通过ioc容器管理对象,ioc容器实质上就是一个对象工厂,使用BeanFactory工厂接口或子接口来实例化ioc容器。

  5、spring的对象工厂结构 

二、ioc怎么用

  1、XML文件配置ioc

   一般把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="demo" class="com.test.Demo" scope="singleton" init-method="init" destroy-method="destroy"></bean>
</beans>

 

    

  (1)实例化bean的方式

  空参构造函数的xml配置如下,Demo类中必须存在空参构造函数Demo()

<bean id="demo" class="com.test.Demo"></bean>

  静态工厂的xml配置如下,getDemo为工厂类创建Demo对象的的静态方法

<bean id="beanFactory"class="com.test.BeanFactory" factory-method="getDemo"></bean>

  实例工厂的xml配置如下,createDemo为工厂类创建Demo对象的的普通方法

<bean id="beanFactory" class="com.test.BeanFactory"></bean>
<bean id="demo" factory-bean="beanFactory" factory-method="createDemo"></bean>

  (2)DI 依赖注入

    DI(Dependency Injection)依赖注入,是ioc的具体实现,ioc降低了类之间的耦合度,但类之间的依赖关系依然存在,这时就需要spring的DI来维护依赖关系。

xm配置文件如下

<bean id="demo" class="com.test.Demo">
        <constructor-arg name="name" value="张三"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>

 

xm配置文件如下

<bean id="demo" class="com.test.Demo">
        <property name="name" value="张三" ></property>
        <property name="age" value="18"></property>
        <property name="birthday" ref="now"></property>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>

  

 xm配置文件如下

<bean id="demo" class="com.test.Demo" p:name="张三" p:age="18" />

  2、注解配置ioc

 

    配置文件applicationContext.xml必须添加如下配置,扫描包及子包下所有类,spring才能侦测到注解标识的组件。<context:component-scan> 元素会自动注册一个bean的后置处理器:AutowiredAnnotationBeanPostProcessor的实例。该后置处理器可以自动装配标记了注解的属性。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.test"></context:component-scan>
</beans>
    如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类。
<context:component-scan base-package="com.test" resource-pattern="autowire/*.class"/>

  3、全注解配置 ioc

    可以完全不写xml配置文件,全部使用注解完成配置。

 

猜你喜欢

转载自www.cnblogs.com/okho-ice/p/12804449.html