Spring笔记02注解IOC

2次阅读

共计 7499 个字符,预计需要花费 19 分钟才能阅读完成。

1. Spring 整合连接池

1.1 Spring 整合 C3P0

  • 在工程中导入 c3p0 连接池需要的包 com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
  • c3p0 的硬编码方式

    @Test    // 自己 new 对象,自己设置属性
        public void test() throws Exception {ComboPooledDataSource dataSource = new ComboPooledDataSource();
            // 设置驱动
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            // 设置地址
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/hibernate");
            // 设置用户名
            dataSource.setUser("root");
            // 设置密码
            dataSource.setPassword("2626");
            // 获取链接池连接对象
            Connection con = dataSource.getConnection();
            System.out.println(con);
            //com.mchange.v2.c3p0.impl.NewProxyConnection@26ba2a48
        }
  • Spring 整合 c3p0 连接池
  • 配置文件

    <!-- c3p0 -->
        <bean id="C3P0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate"></property>
            <property name="user" value="root"></property>
            <property name="password" value="2626"></property>
        </bean>
  • 测试

    @Test    //Spring 的 IOC+DI 替代以上硬编码的方式
        public void test2() throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            DataSource dataSource = (DataSource) context.getBean("C3P0");
            Connection con = dataSource.getConnection();
            System.out.println(con);
            //com.mchange.v2.c3p0.impl.NewProxyConnection@52aa2946
        }

1.2 Spring 整合 DBCP

  • 导入 DBCP 连接池需要的包 com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar 和 com.springsource.org.apache.commons.pool-1.5.3.jar
  • DBCP 硬编码方式

    @Test    //DBCP 的硬编码方式
        public void test3() throws SQLException {BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/hibernate");
            dataSource.setUsername("root");
            dataSource.setPassword("2626");
            Connection con = dataSource.getConnection();
            System.out.println(con);
            //jdbc:mysql://localhost:3306/hibernate, UserName=root@localhost, MySQL-AB JDBC Driver
        }
  • Spring 整合 DBCP
  • 配置文件

    <!-- DBCP -->
        <bean id="DBCP" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/hibernate"></property>
            <property name="username" value="root"></property>
            <property name="password" value="2626"></property>
        </bean>
  • 测试

    @Test
        public void test4() throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            DataSource dataSource = (DataSource) context.getBean("DBCP");
            Connection con = dataSource.getConnection();
            System.out.println(con);
            //jdbc:mysql://localhost:3306/hibernate, UserName=root@localhost, MySQL-AB JDBC Driver
        }

1.3 最终版

  • 最终版使用 propertie 配置文件,Spring 加载 properties 文件
  • Spring 提供了一个标签可以加载外部的 properties 文件内容
  • 导入 context 的名称空间和约束后,xml 文件中才会有提示,这个约束在 /spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html 中可以找到

    <?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"> <!-- bean definitions here -->
    </beans>
  • 导入约束后配置 xml

    <context:property-placeholder location="classpath:jdbc.properties"/>
    
        <!-- DBCP -->
        <bean id="DBCP" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
  • 测试

    @Test
        public void test4() throws SQLException {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            DataSource dataSource = (DataSource) context.getBean("DBCP");
            Connection con = dataSource.getConnection();
            System.out.println(con);
            //jdbc:mysql://localhost:3306/hibernate, UserName=root@localhost, MySQL-AB JDBC Driver
        }
  • jdbc.properties 配置文件可以配置不同的数据库,切换方便。

2. 基于注解的 IOC 配置

  • 注解配置和 xml 配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置形式不一样。至于是使用 xml 还是注解,实际的开发过程中,每家公司有不同的习惯。

2.1 导包

  • 拷贝必备包到 lib 目录下。基于注解的配置中,需要加入一个 aop 的 jar 包。

2.2 配置文件

  • 基于注解的配置文件,导入约束时需要多导入一个 context 名称空间下的约束。约束的位置可以在约束的位置在:

    ​ ..spring-framework-4.2.4.RELEASEdocsspring-framework-referencehtmlxsd-configuration.html 中找到

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:context="http://www.springframework.org/schema/context"
           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
                    http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context.xsd ">
    </beans>

2.3 开启注解扫描器

  • 在配置文件中开启注解扫描器

    <!-- 开启注解扫描器
            com.itzhouq:包含自己以及自己下面的所有子包
     -->
    <context:component-scan base-package="com.itzhouq"></context:component-scan>
            
  • 告知 Spring 框架,在读取配置文件,创建容器时,依据注解创建对象,并存入容器中

2.4 使用注解

  • 要创建 UserDaoImpl 对象,在类上使用 @Component 注解。只要定义在类上,那么注解扫描器只要一扫描到就会创建该类的实例对象,放入 Spring 容器中。

    package com.itzhouq.daoImpl;
    
    import org.springframework.stereotype.Component;
    
    import com.itzhouq.dao.UserDao;
    
    @Component("userDao")    //<bean id="userDao" class="com.itzhouq.daoImpl.UserDaoImpl"></bean>
    public class UserDaoImpl implements UserDao{
    
        @Override
        public void save() {System.out.println("操作数据库,保存用户的数据");
        }
    }
  • 要创建的对象 UserServiceImpl,在类上使用注解,在属性上使用注解
  • @value(“ 属性值 ”):定义在属性字段上,针对的是基本数据类型和 String 类型。如果使用了这个注解,该属性的 set 方法可以省略不写。
  • @Autowired:定义在属性字段上,针对的是对象类型。自动按照类型注入,当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注解的对象变量名作为 bean 的 id,在 Spring 容器查找,找到了也可以注入成功,找不到就报错。
  • @Qualifier(“ 对象属性 id”):定义在属性字段上。在自动按照类型注入的基础上,再按照 Bean 的 id 注入。他在给字段注入时,不能独立使用,必须和 @Autowired 一起使用。但是给方法参数注入时,可以独立使用。

    package com.itzhouq.serviceImpl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import com.itzhouq.dao.UserDao;
    import com.itzhouq.daoImpl.UserDaoImpl;
    import com.itzhouq.service.UserService;
    
    @Component("userService")    //<bean id="UserService" class="com.itzhouq.serviceImpl.UserServiceImpl">
    public class UserServiceImpl implements UserService {@Value("要开始访问 dao 了")    //<property name="name" value="要开始访问 dao 了"></property>
        private String name;    // 使用注解,可以不需要 set 方法,相当于直接赋值
        
        @Autowired    // 对象类型:自动去 Spring 容器中找有没有该类型(UserDao)的实例对象  如果有直接赋值
        @Qualifier("userDao")
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {this.userDao = userDao;}
    
        @Override
        public void save() {System.out.println(name);
            // 调用 dao
            userDao.save();}
    }
  • 测试

    @Test
        public void test() {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.save();
            // 要开始访问 dao 了
            // 操作数据库,保存用户的数据
        }

2.5 了解的几个注解

  • @Scope(“singleton”) / @Scope(“prototype”):定义在类上,用于指定该类是单实例还是多实例

    • 一般 action/web 层为多实例,service 和 dao 层为单实例
  • @PostConstruct:定义在方法上,用于配置初始化方法
  • @PreDestroy:定义在方法上,用于配置销毁的方法

3. Spring 整合 JUnit

3.1 导入包

  • spring-aop-4.2.4.RELEASE.jar
  • spring-test-4.2.4.RELEASE.jar
  • junit.jar

3.2 编写测试类

package com.itzhouq.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.itzhouq.service.UserService;

//1. 告诉 Spring 配置文件的位置
//2. 告诉 Spring 谁去加载配置文件
@ContextConfiguration(value="classpath:applicationContext.xml")
@RunWith(value=SpringJUnit4ClassRunner.class)
public class SpringJunit {
    @Autowired
    private UserService userService;
    
    @Test
    public void test() {userService.save();
//        要开始访问 dao 了
//        操作数据库,保存用户的数据
    }
}

3.3 注解

  • 使用 @RunWith 注解替换原有运行器
  • 使用 @ContextConfiguration 指定 spring 配置文件的位置
  • 使用 @Autowired 给测试类中的变量注入数据
正文完
 0