DI、IOC基础学习笔记

204 阅读9分钟

spring 优点

  • 方便解耦,简化开发(高内聚低耦合)
    • Spring就是一个大厂(容器),可以将所有对象创建和依赖关系维护,交给Spring管理
  • AOP编程的支持
    • Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
  • 声明式事务的支持
    • 只需要通过配置基于可以完成对事务的管理,而无需手动编程
  • 方面程序的测试
    • spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如Struts、Hibernate、MyBatis、Quartz等)的直接支持
  • 降低JavaEEAPI的使用难度
    • spring对JAVAEE开发中非常难用的一些API(JDBC,JavaMail,远程调用等),都提供了封装,使这些API应用难度大大降低

案例入门 IOC

  1. 导入jar包

    1. 4+1:四个核心(beans、core、context、expression)+1个依赖(commons-loggins..jar)
  2. 目标类

    1. 提供UserService接口和实现

    2. 获得UserService实现类的实例

    3. 之前开发,直接new一个对象即可,学习spring之后,将由Spring创建对象实例-->IOC控制反转(Inverse of Control)之后需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中

      ``

      public interface UserService {
          public void addUser();
      }
      
      public class UserServiceImpl implements UserService{
      
          @Override
          public void addUser() {
              System.out.println("Hello world");
          }
      }
      
      
    @Test
    public void test(){
        //从spring容器获得
        //1获得容器
        String xmlPath = "com/adolph/ioc/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        //2获得内容--不需要自己new,都是从spring容器中获得
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
    
    }
    
  3. 配置文件

    1. 位置:任意,开发中一般在classpath下
    2. 名称:任意,开发中常用applicationContext.xml
    3. 内容:添加schema约束

    ``

    <?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">
    
        <!--配置server
            <bean>配置需要创建的对象
                id:用于之后从spring容器获得实例时使用的
                class:需要创建实例的全限定类名
        -->
        <bean id="userServiceId" class="com.adolph.ioc.UserServiceImpl"></bean>
    </beans>
    

案例入门 DI

  • DI(Dependency Injection)依赖注入

    • is a:是一个,继承

    • has a:有一个,成员变量,依赖

      class B{

      private A a; //B类依赖A

      }

      依赖:一个对象需要使用另一个对象

      注入:通过setter方法进行另一个对象的实例设置

      例如:

      class BookService{
    
      	//之前开发(service和dao耦合)
    
      	private BookDao bookDao = new BookDaoImpl();
    
      	//spring之后(解耦:service实现类使用dao接口,不知道具体的实现类)
    
      	private BookDao bookDao;
    
      }
    

模拟spring执行过程

创建service实例:BookServlice bookService = new BookService() -->IOC

创建dao实例:BookDao bookDao = new BookDaoImpl() -->IOC

将dao设置给service:bookService.setBookDao(bookDao) -->DI

目标类

创建BookService接口和实现类

创建BookDao接口和实现

将dao和service配置xml文件

``

<!--<property>用于进行属性名注入
name:bean的属性名,通过setter方法获得setBookDao
 ref:另一个bean的id值的引用##-->
<!--创建service执行过程-->
<bean id="bookServiceId" class="com.adolph.di.BookServiceImpl">
    <property name="bookDao" ref="bookDaoId"></property>
</bean>

<bean id="bookDaoId" class="com.adolph.di.BookDaoImpl"></bean>

核心 API

  • BeanFactory:这是一个工厂,用于生成任意bean。采用延时加载,第一次getBean时才会初始化Bean
  • ApplicationContext:是BeanFactory的子接口,功能更强大
    • 国际化处理
    • 事件传递
    • Bean自动装配
    • 各种不同应用层Context的实现
  • CalssPathXmlApplicationContext用于加载classpath(类路径、src)下指定的xml
  • FileSystemXmlApplicationCotext 用于加载指定盘符下的xml

基于XML

1、实例化方式

3种备案实例化方式:默认构造、静态工厂、实例工厂

  1. 默认构造

    1. 必须提供默认构造
  2. 静态工厂

    1. 常用于与spring整合其他框架(工具)

    2. 静态工厂:用于生成实例对象,所有的方法必须是static

    3. 实例工厂

      1. 必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是“非静态“的。

      ``

      public class MyBeanFactory {
          /**
           * 创建实例
           * @return
           */
          public  UserService createService(){
              return new UserServiceImpl();
          }
      }
      

      ``

       <!--创建工厂实例-->
      <bean id="myBeanFactory" class="com.adolph.inject.b_static_factory.MyBeanFactory"></bean>
      
       <!--获得userService
      	factory-bean 确定工厂实例
      	factory-method 确定普通方法
      -->
       <bean id="userService" factory-bean="myBeanFactory" factory-method="createService"></bean>
      

2、Bean种类

  • 普通bean:之前操作的都是普通bean。,spring直接创建A实例,并返回
  • FactoryBean:是一个特殊的bean具有工厂生成对象的能力,只能生成特定的对象。bean必须使用Factory接口,此接口提供方法getObject()方法用于获得特定bean先创建FB实例,使用调用getObject()方法,并返回方法的返回值。FB fb = new FB(); return fb.getObject();
  • BeanFactory和FactoryBean对比
    • BeanFactory:工厂,用于生产任意的bean
    • FactoryBean:特定bean,用于生成另一个特定的bean。 例如:ProxyFactoryBean,此工厂bean用于生产代理。获得代理对象实例。AOP的使用

3、作用域

作用域:用于确定spring创建bean实例个数
类别 说明
singleton 在spring Ioc容器中仅存在一个Bean实例,Bean亦单例方式存在,默认值
prototype 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行new XXBean()
request 每次HTTP请求都会创建一个新的Bean。该作用域仅适用于WebApplicationContext环境
session 同一个HTTP Session 共享一个Bean,不同Session使用不同的Bean,仅适用于WebApplicationContext环境
globalSession 一般用于Portlet应用环境,该作用域仅适用于WebApplicationContext环境
  • 取值

    • singleton 单例,默认值。
    • prototype 多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例
  • 配置信息

<bean id="userService" class="com.adolph.inject.b_static_factory.UserServiceImpl" scope="prototype"></bean>

4、生命周期

4.1、初始化和销毁
  • 目标方法执行或执行后,将进行初始化或销毁

    <bean id="" class="" init-method="初始化方法名称" destroy-method="销毁的方法名称">
    

    实例

            public void myInit(){
                System.out.println("初始化");
            }

            public void myDestroy(){
                System.out.println("销毁");
            }
        }

        //要求:1,容器必须close,销毁方法执行,2、必须是单例的
        //此方法接口中没有定义,实现类提供
        classPathXmlApplicationContext.close();
    <!--
        init-method:用于配置初始化方法,准备数据
        destroy-method:用于配置销毁方法,清理资源
    -->
    <bean id="userServiceId" class="com.adolph.ioc.UserServiceImpl" init-method="myInit" destroy-method="myDestroy"></bean>
4.2、BeanPostProcessor 后处理Bean
  • spring 提供一种机制、只要实现接口BeanPostProcessor,并将实现类提供给spring容器,spring容器将自动执行,在初始化方法前执行before(),在初始化方法后执行after() 。配置

  • spring提供工厂勾子,用于修改实例对象,可以生成代理对象,是AOP底层。

    模拟:

    //将a的实例对象传递给后处理bean,可以生成代理对象并放回 
    A a = new A();
    a = B.before(a);
    a.init();
    a = B.after(a)   //生成代理对象,目的在目标方法前后执行(例如:开启事务,提交事务)
    a.addUser();
    a.destroy();
    
    
    
    public class MyBeanPostProcessor implements BeanPostProcessor {
    
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("前方法" + beanName);
            return null;
        }
    
        @Override
        public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
            System.out.println("后方法" + beanName);
            return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler(){
    
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("------开启事务");
    //                        执行目标方法
                            Object obj = method.invoke(bean, args);
    
                            System.out.println("------提交事务");
                            return obj;
                        }
                    });
        }
    
    
    }
    
<bean class="com.adolph.ioc.MyBeanPostProcessor"></bean>

4.3、setter方法

``

<bean id="person" class="com.adolph.stter.Person">
    <property name="pname" value="jack"></property>
    <property name="age">
        <value>18</value>
    </property>
    <property name="address" ref="address"></property>
</bean>

<bean  id="address" class="com.adolph.stter.Address">
    <property name="addr" value="湖南"></property>
    <property name="tel"    value="177*****43"></property>
</bean>
4.4P命名空间

,默认:xmlns=""

显示:xmlns:别名=""

4.5、SqEL
  • 对进行统一编码,所有内容都是使用value
  • #{123}、#{'jack'}:数字、字符串
  • #{beanId}:另一个bean引用
  • #{beanId.propName}:操作数据
  • #{beanId.toString}:执行方法
  • #{T(类).字段|方法}:静态方法或字段
4.6、集合注入
public class CollData {

    private String[] arrrayData;

    private List<String> listData;

    private Set<String> setData;

    private Map<String,String> mapData;

    private Properties properties;

    public String[] getArrrayData() {
        return arrrayData;
    }

    public void setArrrayData(String[] arrrayData) {
        this.arrrayData = arrrayData;
    }

    public List<String> getListData() {
        return listData;
    }

    public void setListData(List<String> listData) {
        this.listData = listData;
    }

    public Set<String> getSetData() {
        return setData;
    }

    public void setSetData(Set<String> setData) {
        this.setData = setData;
    }

    public Map<String, String> getMapData() {
        return mapData;
    }

    public void setMapData(Map<String, String> mapData) {
        this.mapData = mapData;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "CollData{" +
                "arrrayData=" + Arrays.toString(arrrayData) +
                ", listData=" + listData +
                ", setData=" + setData +
                ", mapData=" + mapData +
                ", properties=" + properties +
                '}';
    }
}

  <!--
        集合的注入都是给<property>添加子标签
        数组:<array>
        List:<list>
        Set:<set>
        Map:<map>
        Properties:<props>

        普通数据:<value>
        引用数据:<ref>
    -->
    <bean id="collData" class="com.adolph.coll.CollData">
        <property name="arrrayData">
            <array>
                <value>1</value>
                <value>2</value>
                <value>3</value>
                <value>4</value>
            </array>
        </property>
        <property name="listData">
            <list>
                <value>1</value>
                <value>2</value>
                <value>3</value>
                <value>4</value>
            </list>
        </property>
        <property name="setData">
            <set>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </set>
        </property>
        <property name="mapData">
            <map>
                <entry key="1" value="a"></entry>
                <entry key="2" value="b"></entry>
                <entry key="3" value="c"></entry>
            </map>
        </property>
        <property name="properties">
                <props>
                    <prop key="高富帅"></prop>
                    <prop key="白富美"></prop>
                    <prop key="屌丝"></prop>
                </props>
        </property>

    </bean>

基于注释

  • 注解:就是一个类,使用@注解名称
  • 开发中:使用注解 取代xml配置文件。
  1. @Component("id")取代

  2. wen开发,提供3个@Component注解衍生注解(功能一样)

    1. @Repository:dao层
    2. @Service:service层
    3. @Controller:web层
  3. 依赖注入,可以给私有字段设置,也可以给setter方法设置

    1. 普通值:@Value("")
    2. 引用值:
      1. 方式1:按照【类型】注入
        1. @Autowired
      2. 方式2:按照【名称】注入1
        1. @Autowired
        2. @Qualifier("名称")注入
      3. 方式3:按照【名称】注入2
        1. @Resource(“名称”)
    • @Test
       public void test() {
           String xmlPath = "com/adolph/web/beans.xml";
           ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
           StudentAction studentAction = applicationContext.getBean("studentActionId", StudentAction.class);
           studentAction.execute();
       }
      
      
      Controller("studentActionId")
      public class StudentAction {
      
          @Autowired
          private StudentService studentService;
      
          public void execute(){
              studentService.add();
          }
      }
      
      @Service
      public class StudentServiceImpl implements StudentService {
      
      
          private StudentDao studentDao;
      
          @Autowired
          @Qualifier("studentDaoId")
          public void setStudentDao(StudentDao studentDao) {
              this.studentDao = studentDao;
          }
      
          @Override
          public void add() {
              studentDao.add();
          }
      }
      
      @Repository("studentDaoId")
      public class StudentDaoImpl implements StudentDao{
          @Override
          public void add() {
              System.out.println("dao");
          }
      }
      
      
      

      生命周期

      ​ 初始化:@PostConstruct

      ​ 销毁:@PreDestroy

      作用域:

      ​ @Scope("prototype") 多例

  4. 注解使用前提,添加命名空间,让spring扫描含有注解类**

      <!--组件扫描-->
     <context:component-scan base-package="com.adolph.annotation"></context:component-scan>