Spring笔记02

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.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: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给测试类中的变量注入数据

Spring笔记02_注解_IOC的更多相关文章

  1. Spring笔记04_AOP注解开发_模板_事务

    目录 1. Spring基于AspectJ的注解的AOP开发 1. 1 SpringAOP的注解入门 1.2 Spring的AOP的注解通知类型 1.2.1 @Before:前置通知 1.2.2 @A ...

  2. Spring笔记13--SSH--全注解开发

    SSH全注解开发: (1) 在Action类中添加注解,实现Struts2的注解开发(@NameSpace.@ParentPackage.@Action...) package com.tongji. ...

  3. spring笔记--通过注解(annotation)配置Bean

    Spring能够在classpath下自动扫描,侦测和实例化具有特定注解的组件,这在Spring中成为组件扫描(Component scanning). 特定组件的注解包括: @Component:基 ...

  4. spring笔记-@Primary注解

    1.问题 当一个接口有2个不同实现时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionExceptio ...

  5. Spring学习笔记--使用注解装配

    使用@Autowired注解 从Spring2.5开始,最有趣的一种装配Spring Bean的方式是使用注解自动装配Bean的属性.Spring默认禁用注解装配,最简单的启用方式是使用Spring的 ...

  6. Spring笔记(5) - 声明式事务@EnableTransactionManagement注解源码分析

    一.背景 前面详解了实现Spring事务的两种方式的不同实现:编程式事务和声明式事务,对于配置都使用到了xml配置,今天介绍Spring事务的注解开发,例如下面例子: 配置类:注册数据源.JDBC模板 ...

  7. springmvc学习笔记(常用注解)

    springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...

  8. 学习笔记_J2EE_SpringMVC_03_注解配置_@RequestMapping用法

    @RequestMappingde的用法 摘要: 主要介绍注解@RequestMapping的用法 一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMappi ...

  9. Spring笔记01_下载_概述_监听器

    目录 Spring笔记01 1.Spring介绍 1.1 Spring概述 1.2 Spring好处 1.3 Spring结构体系 1.4 在项目中的架构 1.5 程序的耦合和解耦 2. Spring ...

随机推荐

  1. synchronized 与 volatile 原理 —— 内存屏障的重要实践

    单例模式的双重校验锁的实现: 第一种: private static Singleton _instance; public static synchronized Singleton getInst ...

  2. 俄罗斯方块(三):"流动"的方块

    问题的提出: 俄罗斯方块允许90度的坡,是不是有点不够科学#(滑稽) 想办法加一种会“滑坡”的方块 本文两大部分: 详细的描绘是怎样的“流动” 写代码,并整合进游戏 本文基于我写的 俄罗斯方块(一): ...

  3. Hadoop 集群安装(主节点安装)

    1.下载安装包及测试文档 切换目录到/tmp view plain copy cd /tmp 下载Hadoop安装包 view plain copy wget http://192.168.1.100 ...

  4. css3 js 做一个旋转音乐播放开关

    我们经常会看到一些旋转音乐播放开关,今天我也写了一个分享出来,大家需要的话可以参考一下: <!DOCTYPE html> <html lang="en"> ...

  5. [Swift]LeetCode107. 二叉树的层次遍历 II | Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...

  6. 微信小程序请求API接口PHPSESSID变化的解决方式

    微信小程序开发,请求服务器API的方法使用的是微信官方提供的wx.request()方法.在开发中发现,每一个请求都会生成一个独立的PHPSESSID,如下图示: 搜索后得知,这是由于wx.reque ...

  7. python之zipfile

    1 简述 zip文件是一个常用的归档和与压缩标准. zipfile模块提供了创建.读取.写入.添加及列出zip文件的工具. zipfile里有2个非常常用的class,分别是Zipfile和ZipIn ...

  8. Heacher互助平台需求分析

    课程属性 作业课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass1/ 作业链接 https://edu.cnblogs.co ...

  9. Java语言的简单基础

    1.Java 是一种高级程序设计语言. 2.Java 是大小敏感的程序语言. 3.Java 中的 public 修饰的类名一般要与文件名相同,但也有特列:内部类. 4.Java 程序能在任何操作系统中 ...

  10. linux静态ip的设置

    我们经常使用虚拟机安装(我使用的linux版本是CentOS6.5),然后配置服务器的web环境,用于程序的调试.默认情况下,linux使用动态ip,每次启动linux时,它的ip地址都有可能发生变化 ...