一:程序之间的耦合及解决

  耦合性(Coupling):也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。耦合性存在于各个领域,而非软件设计中独有的。
  在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。划分模块的一个准则就是高内聚低耦合。

1:耦合的分类

①:内容耦合:
  当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
②:公共耦合:
  两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
③: 外部耦合 :
  一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。
④: 控制耦合 :
  一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。
⑤:标记耦合 :
  若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。
⑥: 数据耦合:
  模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。
⑦: 非直接耦合 :
  两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。

2:耦合总结

  耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。

3:扩展(内聚和耦合的使用)

  内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。内聚是从功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。 程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同其他模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合。

4:呈现耦合的代码片段

  1. ##### 第一种常见的耦合状态
  2. /**
  3. * 学生业务处理实现类
  4. * @author ant
  5. */
  6. public class StudentServiceImpl implements StudentService {
  7.  
  8. //组合了持久层对象
  9. private StudentDao studentDao = new StudentDaoImpl();
  10.  
  11. /**
  12. * @method 模拟保存学生方法实现
  13. */
  14. public void save() {
  15. //调用dao的保存数据方法
  16. studentDao.save();
  17. }
  18. }
  19. // 业务层调用持久层,并且此时业务层在依赖持久层的接口和实现类。
  20. // 如果此时没有持久层实现类,编译将不能通过。这种编译期依赖关系,
  21. // 应该在我们开发中杜绝。我们需要优化代码解决。
  22.  
  23. ##### 第二种耦合
  24. // 问题:在JDBC注册驱动时我们为什么不使用 DriverManager 的 registerDriver 方法,而是采用 Class.forName("xxx") 的方式?
  25.  
  26. //1.注册驱动
  27. //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 为什么不使用这个
  28. Class.forName("com.mysql.jdbc.Driver");
  29. //2.获取连接
  30. //3.获取预处理 sql 语句对象
  31. //4.获取结果集
  32. //5.遍历结果集
  33.  
  34. // 回答:其实我们的类依赖了数据库的具体驱动类(MySQL),
  35. // 如果使用registerDriver方法注册,会存在一定的耦合,依赖具体的驱动类,如果不存在com.mysql.jdbc.Driver类,则运行都不行,
  36. // 而Class.forName则解决了这种问题,因为它是接收字符串,不在依赖具体驱动类,同时,也产生了一个新的问题,mysql 驱动的全限定类名字符串是在 java 类中写死的,一旦要改还是要修改源码。解决这个问题也很简单,使用配置文件配置。不使用工厂模式展示代码耦合

程序耦合的2个小实例

5:使用工厂模式解耦

  在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂

工厂创建的对象存在哪呢?:

  那肯定要要找个集合来存。这时候有 Map 和 List 供选择。到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。所以我们的答案就是在应用加载时,创建一个 Map,用于存放三层对象。我们把这个 map 称之为容器。

什么是工厂呢?:

  工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。

 ①:不使用工厂模式之前的耦合代码

  1. #####StudentDao接口
  2.  
  3. public interface StudentDao {
  4. /**
  5. * @method 模拟保存学生接口方法
  6. */
  7. void save();
  8. }
  9.  
  10. +++++++++++++++++++++++++++++++++++++++++
  11. #####StudentDao接口实现类
  12.  
  13. public class StudentDaoImpl implements StudentDao {
  14. /**
  15. * @method 模拟保存学生方法实现
  16. */
  17. public void save() {
  18. System.out.println("==》保存完成《==");
  19. }
  20. }
  21.  
  22. +++++++++++++++++++++++++++++++++++++++++
  23. ##### StudentService业务接口
  24.  
  25. public interface StudentService {
  26. /**
  27. * @method 模拟保存学生接口方法
  28. */
  29. void save();
  30. }
  31.  
  32. +++++++++++++++++++++++++++++++++++++++++
  33. ##### StudentServiceImpl 业务接口实现类
  34.  
  35. /**
  36. * 学生业务处理实现类
  37. * @author ant
  38. */
  39. public class StudentServiceImpl implements StudentService {
  40. //组合
  41. private StudentDao studentDao = new StudentDaoImpl();
  42.  
  43. /**
  44. * @method 模拟保存学生方法实现
  45. */
  46. public void save() {
  47. //调用dao的保存数据方法
  48. studentDao.save();
  49. }
  50. }
  51.  
  52. +++++++++++++++++++++++++++++++++++++++++
  53. ##### 测试类
  54.  
  55. public class Client {
  56. public static void main(String[] args) throws SQLException {
  57. //创建StudentService对象实体后调用操作
  58. StudentService studentService=new StudentServiceImpl();
  59. studentService.save();
  60. }
  61. }
  62.  
  63. //这个就是我们平常写的三层架构,成功的展示了代码的耦合,这时候随便删除一个类代码都会报代码错误

不使用工厂模式展示代码耦合

②:使用工厂模式进行解耦

  1. ##### 第一种工厂对象 产生的是多例对象
  2. /**
  3. * 第一种它是多例,这个工厂效率低,因为每次调用都要重新匹配,
  4. * 然后获取和实例化返回,来回创建对象,会对程序的性能有所影响
  5. */
  6. public class BeanFactory {
  7. //聚合Properties配置类
  8. private static Properties prop;
  9. //初始化Properties数据
  10. static {
  11. prop = new Properties();
  12. try {
  13. //获取文件加载到Properties对象里
  14. prop.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
  15. } catch (Exception e) {
  16. throw new RuntimeException("读取配置失败");
  17. }
  18. }
  19. //根据键获取相应对象
  20. public static Object getBean(String name) {
  21. //根据键获取value
  22. String property = prop.getProperty(name);
  23. Object obj = null;
  24. try {
  25. //通过反射获取对象实例 每次都重新实例化
  26. obj = Class.forName(property).getConstructor().newInstance();
  27. } catch (Exception e) {
  28. throw new RuntimeException("无法注册");
  29. }
  30. //返回对象
  31. return obj;
  32. }
  33. }
  34.  
  35. +++++++++++++++++++++++++++++++++++++++++
  36. ##### 第二种工厂对象 产生的是单例对象
  37. /**
  38. * 这种是简单的单例工厂,把数据全部存放于容器中,然后要的时候获取,
  39. */
  40. public class BeanFactory {
  41. //聚合Properties配置类
  42. private final static Properties prop;
  43. //创建容器存储对象
  44. private final static Map<String, Object> beans;
  45.  
  46. //初始化
  47. static {
  48. //为2个对象赋值
  49. prop = new Properties();
  50. beans = new HashMap<String, Object>();
  51. try {
  52. //获取文件加载到Properties对象里
  53. prop.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
  54. //获取配置文件全部key
  55. Enumeration<Object> keys = prop.keys();
  56. //循环获取值 然后实例化存储到map容器
  57. while (keys.hasMoreElements()) {
  58. String key = keys.nextElement().toString();
  59. String value = prop.getProperty(key);
  60. Object bean = Class.forName(value).getConstructor().newInstance();
  61. beans.put(key, bean);
  62.  
  63. }
  64. } catch (Exception e) {
  65. throw new RuntimeException("读取配置失败");
  66. }
  67. }
  68.  
  69. //根据键获取相应对象
  70. public static Object getBean(String name) {
  71. //从容器获取返回
  72. if (beans.containsKey(name)) {
  73. return beans.get(name);
  74. }
  75. return null;
  76. }
  77. }

工厂的2种写的方式

  1. ##### StudentDao持久层接口
  2. public interface StudentDao {
  3. /**
  4. * @method 模拟保存学生接口方法
  5. */
  6. void save();
  7. }
  8.  
  9. +++++++++++++++++++++++++++++++++++++++++
  10. ##### StudentDaoImpl持久层接口实现类
  11. public class StudentDaoImpl implements StudentDao {
  12. /**
  13. * @method 模拟保存学生方法实现
  14. */
  15. public void save() {
  16. System.out.println("==》保存完成《==");
  17. }
  18. }
  19.  
  20. +++++++++++++++++++++++++++++++++++++++++
  21. ##### StudentService业务层接口
  22. public interface StudentService {
  23. /**
  24. * @method 模拟保存学生接口方法
  25. */
  26. void save();
  27. }
  28.  
  29. +++++++++++++++++++++++++++++++++++++++++
  30. ##### StudentServiceImpl业务接口实现类
  31. public class StudentServiceImpl implements StudentService {
  32. //聚合StudentDao接口
  33. private static StudentDao studentDao;
  34. //初始化
  35. static{
  36. studentDao = (StudentDaoImpl)BeanFactory.getBean("studentDao");
  37. }
  38. /**
  39. * @method 模拟保存学生方法实现
  40. */
  41. public void save() {
  42. //调用dao的保存数据方法
  43. studentDao.save();
  44. }
  45. }
  46.  
  47. +++++++++++++++++++++++++++++++++++++++++
  48. ##### 测试类
  49. public class Client {
  50. public static void main(String[] args) throws SQLException {
  51. //创建StudentService对象实体后调用操作
  52. StudentService studentService=(StudentServiceImpl) BeanFactory.getBean("studentService");
  53. studentService.save();
  54. }
  55. }

基本代码及测试

  1. studentDao=cn.xw.dao.impl.StudentDaoImpl
  2. studentService=cn.xw.service.impl.StudentServiceImpl

bean.properties配置文件

小总结:其实我们在日常开发中,都是不用手动写控制反转(解耦)都是由Spring帮我们完成了,因为Spring核心就包括IOC

二:Spring IOC解决程序耦合

1:相应资料

  Spring官网

  注意:我们现在开发用的Spring版本都是5版本以上的,用jdk8编写的,同时tomcat版本也要在8.5以上

  1. <!--编写Spring必须要导入相应坐标-->
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework</groupId>
  5. <artifactId>spring-context</artifactId>
  6. <version>5.2.6.RELEASE</version>
  7. </dependency>
  8. </dependencies>

2:使用Spring实现IOC解决耦合

①:编写Service和Dao接口及实现类

  1. ##### StudentDao持久层接口
  2. public interface StudentDao {
  3. /**
  4. * @method 模拟保存学生接口方法
  5. */
  6. void save();
  7. }
  8.  
  9. +++++++++++++++++++++++++++++++++++++++++
  10. ##### StudentDaoImpl持久层接口实现类
  11. public class StudentDaoImpl implements StudentDao {
  12. /**
  13. * @method 模拟保存学生方法实现
  14. */
  15. public void save() {
  16. System.out.println("==》保存完成《==");
  17. }
  18. }
  19.  
  20. +++++++++++++++++++++++++++++++++++++++++
  21. ##### StudentService业务层接口
  22. public interface StudentService {
  23. /**
  24. * @method 模拟保存学生接口方法
  25. */
  26. void save();
  27. }
  28.  
  29. +++++++++++++++++++++++++++++++++++++++++
  30. ##### StudentServiceImpl业务接口实现类
  31. public class StudentServiceImpl implements StudentService {
  32. //聚合StudentDao接口
  33. private static StudentDao studentDao;
  34. /**
  35. * @method 模拟保存学生方法实现
  36. */
  37. public void save() {
  38. ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  39. studentDao = app.getBean("studentDao", StudentDao.class);
  40.  
  41. //调用dao的保存数据方法
  42. StudentServiceImpl.studentDao.save();
  43. }
  44. }

Dao和Service

②:编写Spring配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. https://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!--把StudentServiceImpl创建放入IOC容器-->
  7. <bean id="studentService" class="cn.xw.service.impl.StudentServiceImpl"></bean>
  8. <!--把StudentDaoImpl创建放入IOC容器-->
  9. <bean id="studentDao" class="cn.xw.dao.impl.StudentDaoImpl"></bean>
  10. </beans>

编写applicationContext.xml

 ③:测试类

  1. public class Client {
  2. public static void main(String[] args) throws SQLException {
  3. ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  4. StudentService studentService = app.getBean("studentService", StudentService.class);
  5. studentService.save();
  6. }
  7. }

测试类代码

进行测试后发现是可以运行的,但是问题来啦,这写的是啥玩意,也看不懂呀,这可咋整,所以这前面代码只是Spring的简单入门,在接下来我就会为大家详细介绍Spring IOC

3:导包的不同方式

  1. 手动导入Springjar
  2. spring-aop-5.0.2.RELEASE.jar
  3. spring-beans-5.0.2.RELEASE.jar
  4. spring-context-5.0.2.RELEASE.jar
  5. spring-core-5.0.2.RELEASE.jar
  6. spring-expression-5.0.2.RELEASE.jar
  7. commons-logging-1.2.jar
  8.  
  9. Maven 我们只需要导入坐标即可
  10. <dependency>
  11. <groupId>org.springframework</groupId>
  12. <artifactId>spring-context</artifactId>
  13. <version>5.2.6.RELEASE</version>
  14. </dependency>
  15. 但是我们看看maven给我们导入的jar
  16. Maven: org.springframework:spring-aop:5.2.6.RELEASE
  17. Maven: org.springframework:spring-beans:5.2.6.RELEASE
  18. Maven: org.springframework:spring-context:5.2.6.RELEASE
  19. Maven: org.springframework:spring-core:5.2.6.RELEASE
  20. Maven: org.springframework:spring-expression:5.2.6.RELEASE
  21. Maven: org.springframework:spring-jcl:5.2.6.RELEASE
  22.  
  23. 问题来啦,大家会看见我们手动导入的loggingmaven导入的jcl其实是一样的
  24. 因为mavenlogging日志jar包封装到了jcl

导包方式

三:Spring之IOC详细介绍(基于XML)

1:Spring中IOC实现的工厂类图结构

2:BeanFactory和ApplicationContext的区别

在上面一个入门的例子中,大家看我都是使用ApplicationContext及它的实现类来加载配置文件和创建容器的,可是它们的区别是什么?我们仔细看BeanFactory是最顶层的接口,而ApplicationContext是它的子接口,唯一的区别是:

ApplicationContext:它在构造核心容器时,创建对象采取的策略是采用立即加载的方式,也就是说,只要一读取完配置文件后就会马上创建配置文件中的对象,然后放入容器中。就像我之前写的第二种工厂方式,把读取的配置文件获取的对象放入Map中。

BeanFactory:它在创建核心容器时,创建对象采取的策略是延迟加载的的方式,也就是说,什么是根据id获取对象的时候才去创建,然后放入容器中

3:ApplicationContext接口的实现类

①:ClassPathXmlApplicationContext

  它可以加载类路径下的任何资源,不在就无法加载,src下的都是类路径,如果在src下是多文件(如在src下的file里面的applicationContext.xml),路径就要写file/applicationContext.xml

②:FileSystemXmlApplicationContext

  加载磁盘下任意文件,必须要有访问权限

③:AnnotationConfigApplicationContext

  用于读取注解,在注解开发会详细说

  1. //加载类路径下的资源
  2. ApplicationContext appA=new ClassPathXmlApplicationContext("applicationContext.xml");
  3. //加载任意文件下的资源
  4. ApplicationContext appB=new FileSystemXmlApplicationContext("D:\\bky_Spring001\\src\\main\\resources\\applicationContext.xml");

4:获取容器对象

  1. //2种获取容器对象的方法
  2. //第一种:参数1 容器id属性 参数2 映射的class对象
  3. StudentService studentServiceA = app.getBean("studentService", StudentService.class);
  4. //第二种: 参数1 容器id属性
  5. StudentService studentServiceB = (StudentServiceImpl)app.getBean("studentService");

5:Spring配置文件bean的三种创建方式

  1. <!--以下面的这个对象为例 下面的3种只能有一种存在-->
  2. <!--第一种 使用默认构造函数创建,前提必须要有无参构造函数,如果没有无参构造函数无法创建-->
  3. <bean id="studentDao" class="cn.xw.dao.impl.StudentDaoImpl"></bean>
  4.  
  5. <!--第二种创建方式 使用工厂方法创建对象-->
  6. <!--factory-bean:引用工厂对象路径 -->
  7. <!--factory-method:调用工厂中的方法 返回一个对象容器-->
  8. <bean id="beanFactory" class="cn.xw.utils.BeanFactory"></bean>
  9. <bean id="studentDao" factory-bean="beanFactory" factory-method="getStudentService"></bean>
  10.  
  11. <!--第三种 使用工厂的静态方法创建对象放到容器中 前提方法必须是静态的-->
  12. <bean id="studentDao" class="cn.xw.utils.BeanFactory" factory-method="getstaticStudentService"></bean>
  1. //工厂对象
  2. public class BeanFactory {
  3. //普通方法
  4. public StudentDao getStudentService(){
  5. return new StudentDaoImpl();
  6. }
  7. //静态方法
  8. public static StudentDao getstaticStudentService(){
  9. return new StudentDaoImpl();
  10. }
  11. }

6:Spring中bean的作用范围(单例或多例)

其实Spring是一个很好的框架,在使用工厂IOC的时候可以指定是单例还是多例

bean标签参数:scope=“xx” 作用范围

  1. ①:singleton:   单例对象  默认
    ②:prototype:  多例对象
    ③:request:    作用域web的请求范围
    ③:session 作用域web的会话范围
    ④:global-session: 作用域web集群会话
  1. <!--把StudentDaoImpl创建放入到IOC容器 并设置了单例对象 默认就是单例-->
  2. <bean id="studentDao" class="cn.xw.dao.impl.StudentDaoImpl" scope="singleton"></bean>

7:Spring中bean生命周期

singleton:单例对象生命周期      prototype:多例对象生命周期
出生:容器创建时对象创建          出生:使用Spring创建,获取时再创建
活着:容器存在,对象一直存在        活着:对象在使用中一直存在
死亡:IOC容器对象销毁,对象也就消亡     死亡:长时间不用会被JVM垃圾回收器回收
总结:和IOC容器的生命周期一样           总结:和我们平时创建对象一样,长时间不用被回收

 ①:单例模式代码演示

  1. <!-更改配置文件-->
  2. <!--把StudentServiceImpl创建放入IOC容器-->
  3. <bean id="studentService" class="cn.xw.service.impl.StudentServiceImpl"
  4. scope="singleton" init-method="init" destroy-method="destroy"></bean>
  1. public class StudentServiceImpl implements StudentService {
  2. //聚合StudentDao接口
  3. private static StudentDao studentDao=new StudentDaoImpl();
  4. /**
  5. * @method 模拟保存学生方法实现
  6. */
  7. public void save() {
  8. //调用dao的保存数据方法
  9. StudentServiceImpl.studentDao.save();
  10. }
  11. //加载方法
  12. public void init(){
  13. System.out.println("对象被 加载了");
  14. }
  15. //销毁方法
  16. public void destroy(){
  17. System.out.println("对象被 销毁了");
  18. }
  19. }
  1. //因为ApplicationContext没有关闭方法,而子类重写了父类方法,还增加了关闭方法,所以改用子类
  2. ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  3. //获取对象 这个是会初始化类 执行init方法
  4. StudentService studentServiceA = app.getBean("studentService", StudentService.class);
  5. //调用主体方法
  6. studentServiceA.save();
  7. //关闭
  8. app.close();

注:单例模式下对象是可以进行关闭的,但是ApplicationContext没有关闭方法,所以要去子类寻找 ,还有 注意一下,Spring5.0.2是可以打印日志的,但是Spring再高版本需要手动设置才可以打印

②:多例模式代码演示

  1. <!--把StudentServiceImpl创建放入IOC容器-->
  2. <bean id="studentService" class="cn.xw.service.impl.StudentServiceImpl"
  3. scope="prototype" init-method="init" destroy-method="destroy"></bean>

其它代码和上面一样,那么为什么关闭方法没有执行?,因为创建的对象为普通对象,Spring不知道你什么时候关闭,所以对象交给JVM垃圾回收器管理

8:Spring依赖注入(重要)

大家在前面有没有发现,我们把对象交给Spring管理的时候,我们之前用的是无参构造方法,可是有个疑问,我要创建带参构造函数怎么办?

  1. public class StudentServiceImpl implements StudentService {
  2. //聚合StudentDao接口
  3. private static StudentDao studentDao;
  4. /**
  5. * @method 模拟保存学生方法实现
  6. */
  7. public void save() {
  8. ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  9. studentDao = app.getBean("studentDao", StudentDao.class);
  10. //调用dao的保存数据方法
  11. StudentServiceImpl.studentDao.save();
  12. }
  13. }

这上面标红的在这里面使用重新加载读取配置文件,重新返回容器里某个对象,是否合适呢?其实是很不合适的,但是Spring已经为我们想到了这些问题,使用依赖注入的方法

依赖注入(Dependency Injection):

  它是Spring框架核心IOC的具体表现,在编程的时候我们通过控制反转交给Spring容器管理对象,但是不能完全实现依赖解耦,这个时候就需要使用到依赖注入了(就是在当前类使用到其他类,这个时候由Spring为当前类提供其它类对象)

IOC作用:降低程序耦合
依赖关系管理:交给Spring完成
依赖注入数据有三种:
  基本类型
  其他bean类型(在bean.xml注解的)
  复杂类型/集合类型

 ①:构造函数注入

  1. public class Student {
  2. private String name;
  3. private int age;
  4. private Date birthday;
  5. private Dog dog;
  6. //省略有参构造函数/get/set/toString
  7. }
  8.  
  9. public class Dog {
  10. private String name;
  11. private String color;
  12. //省略有参构造函数/get/set/toString
  13. }

实体类对象

  1. <!--配置Student对象-->
  2. <bean id="student" class="cn.xw.domain.Student">
  3. <constructor-arg name="name" value="张三"></constructor-arg>
  4. <constructor-arg name="age" value="25"></constructor-arg>
  5. <!--因为birthday是日期类型,所以我要引用下面的一个日期类型-->
  6. <constructor-arg name="birthday" ref="date"></constructor-arg>
  7. <!--因为dog是自定义对象Dog类型,所以我引用下面的Dog对象-->
  8. <constructor-arg name="dog" ref="dog"></constructor-arg>
  9. </bean>
  10. <!--配置Date对象-->
  11. <bean id="date" class="java.util.Date">
  12. <constructor-arg name="date" value="12345644556"></constructor-arg>
  13. </bean>
  14. <!--配置Dog对象-->
  15. <bean id="dog" class="cn.xw.domain.Dog">
  16. <constructor-arg name="name" value="大黄"></constructor-arg>
  17. <constructor-arg name="color" value="黄色"></constructor-arg>
  18. </bean>
  19. <!--
  20. constructor-arg:用来声明构造函数里面的参数的
  21. ++++++++++++用来指定给那个参数赋值++++++++++++
  22. index:使用索引的方式来和构造函数列表匹配 下标0开始
  23. type:用来注入指定数据类型来匹配
  24. name:用来匹配构造函数里参数的名称来赋值 最常用
  25. ++++++++++++设定值++++++++++++
  26. value:直接设置值即可
  27. rel:用来设置那些对象属性,引用其它对象
  28. -->

applicationContext.xml配置文件

  1. public class Client {
  2. public static void main(String[] args) throws SQLException, InterruptedException {
  3. //创建ApplicationContext对象
  4. ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  5. //获取对象
  6. Student student = app.getBean("student", Student.class);
  7. //打印对象
  8. System.out.println(student.toString());
  9. //打印结果:Student{name='张三', age=25, birthday=Sun May 24 05:20:44 CST 1970, dog=Dog{name='大黄', color='黄色'}}
  10. }
  11. }

测试方法

②:set依赖注入

因为set注入必须要有属性的全部set方法,而且还得提供一个无参的构造函数,所以对上面的实体类添加一个无参构造函数,接下来我对配置文件改造成set注入

  1. <!--配置Student对象-->
  2. <bean id="student" class="cn.xw.domain.Student">
  3. <property name="name" value="张三"></property>
  4. <property name="age" value="25"></property>
  5. <!--因为birthday是日期类型,所以我要引用下面的一个日期类型-->
  6. <property name="birthday" ref="date"></property>
  7. <!--因为dog是自定义对象Dog类型,所以我引用下面的Dog对象-->
  8. <property name="dog" ref="dog"></property>
  9. </bean>
  10. <!--配置Date对象-->
  11. <bean id="date" class="java.util.Date">
  12. <property name="time" value="12345644556"></property>
  13. </bean>
  14. <!--配置Dog对象-->
  15. <bean id="dog" class="cn.xw.domain.Dog">
  16. <property name="name" value="大黄"></property>
  17. <property name="color" value="黄色"></property>
  18. </bean>
  19. <!--
  20. property:用于set注入
  21. 注意:set注入是找到set方法后去除set字母把后面的字母全部换成小写
  22. 如:setName(String name)==>setName==>Name==>name==>最终找到name
  23. -->

set注入

③:复杂类型注入

我们前面学习了普通的类型注入,但是如果遇到数组、集合、键值对怎么注入呢?接下来我就带大家来讨论一下!

  1. public class Student {
  2. private String [] arrays; //数组类型
  3. private List<String> list; //有序集合
  4. private Set<String> sets; //无序集合
  5. private Map<String,String> maps;//Map集合
  6. private Properties properties; //properties键值对
  7. public void setArrays(String[] arrays) {
  8. this.arrays = arrays;
  9. }
  10. public void setList(List<String> list) {
  11. this.list = list;
  12. }
  13. public void setSets(Set<String> sets) {
  14. this.sets = sets;
  15. }
  16. public void setMaps(Map<String, String> maps) {
  17. this.maps = maps;
  18. }
  19. public void setProperties(Properties properties) {
  20. this.properties = properties;
  21. }
  22. @Override
  23. public String toString() {
  24. System.out.println(arrays);
  25. System.out.println(list);
  26. System.out.println(sets);
  27. System.out.println(maps);
  28. System.out.println(properties);
  29. return null;
  30. }
  31. }

实体类

  1. <!--配置Student对象-->
  2. <bean id="student" class="cn.xw.domain.Student">
  3. <!--注入数组类型-->
  4. <property name="arrays">
  5. <array>
  6. <value>arraysA</value>
  7. <value>arraysB</value>
  8. <value>arraysC</value>
  9. </array>
  10. </property>
  11. <!--注入集合类型-->
  12. <property name="list">
  13. <list>
  14. <value>listA</value>
  15. <value>listB</value>
  16. <value>listC</value>
  17. </list>
  18. </property>
  19. <!--注入set类型-->
  20. <property name="sets">
  21. <set>
  22. <value>setA</value>
  23. <value>setB</value>
  24. <value>setC</value>
  25. </set>
  26. </property>
  27. <!--注入键值对类型-->
  28. <property name="maps">
  29. <map>
  30. <entry key="mapkeyA" value="mapValueA"></entry>
  31. <entry key="mapkeyB" value="mapValueB"></entry>
  32. <entry key="mapkeyC" value="mapValueC"></entry>
  33. </map>
  34. </property>
  35. <!--注入配置文件类型-->
  36. <property name="properties">
  37. <props>
  38. <prop key="propskeyA" >propsValueA</prop>
  39. <prop key="propskeyB" >propsValueB</prop>
  40. <prop key="propskeyC" >propsValueC</prop>
  41. </props>
  42. </property>
  43. </bean>

applicationContext.xml配置文件

注:Arrays、List、Set是一组 Map、Properties是一组,上面2组同类的标签是可以相互替换的,因为类型都一样,正常单列数据使用List,键值对数据使用Map即可

 9:使用Spring基于XML完成对数据的CRUD操作(基于XML小总结)

本案例实现对学生表的CRUD操作,为了更好的体现出上面讲的知识,我准备使用Spring基于XML开发,因为没有涉及到web页面,所以就建一个maven普通项目,不使用框架,其它技术有MySQL数据库、dbutils工具包、C3P0连接池

资料导入:MySQL建表语句

  1. public class Student {
  2. private int sid; //主键id
  3. private String sname; //姓名
  4. private String ssex; //性别
  5. private int sage; //年龄
  6. private double scredit; //学分
  7. private double smoney; //零花钱
  8. private String saddress; //住址
  9. private String senrol; //入学时间
  10. //因为简单的单表CRUD就不涉及到外键
  11. //private int fid; //外键 连接家庭表信息学生对家庭,一对一
  12. //private int tid; //外键 连接老师信息 学生对老师,一对一
  13. //创建构造器/get/set/toString就不展示了
  14. }

实体类

  1. <dependencies>
  2. <!--mysql驱动-->
  3. <dependency>
  4. <groupId>mysql</groupId>
  5. <artifactId>mysql-connector-java</artifactId>
  6. <version>5.1.32</version>
  7. </dependency>
  8. <!--工具类 操作数据库-->
  9. <dependency>
  10. <groupId>commons-dbutils</groupId>
  11. <artifactId>commons-dbutils</artifactId>
  12. <version>1.7</version>
  13. </dependency>
  14. <!--连接池-->
  15. <dependency>
  16. <groupId>c3p0</groupId>
  17. <artifactId>c3p0</artifactId>
  18. <version>0.9.1.2</version>
  19. </dependency>
  20. <!--Spring坐标-->
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-context</artifactId>
  24. <version>5.2.6.RELEASE</version>
  25. </dependency>
  26. <!--单元测试-->
  27. <dependency>
  28. <groupId>junit</groupId>
  29. <artifactId>junit</artifactId>
  30. <version>4.12</version>
  31. </dependency>
  32. </dependencies>

pom.xml坐标

  1. #####接口
  2. /**
  3. * 学生数据操作Dao接口
  4. * @author ant
  5. */
  6. public interface StudentDao {
  7. //查询全部学生
  8. List<Student> findAll();
  9. //查询多个学生,根据姓名和地址模糊查询
  10. List<Student> findByLikeNameAndLikeAddress(String name, String address);
  11. //查询单个学生根据id
  12. Student findById(Integer id);
  13. //查询学生总数
  14. Integer totalCount();
  15. //添加学生
  16. Integer add(Student student);
  17. //更新学生
  18. Integer update(Student student);
  19. //删除学生
  20. Integer delete(Integer id);
  21. }
  22. +++++++++++++++++++++++++++++++++++++++++
  23.  
  24. ######实现类
  25. /**
  26. * 学生数据操作Dao实现类
  27. * @author ant
  28. */
  29. public class StudentDaoImpl implements StudentDao {
  30. //聚合dbutils工具类
  31. private QueryRunner query;
  32. //有构造方法注入和set注入 这里选择set注入 不修改无参构造器
  33. public void setQuery(QueryRunner query) {
  34. this.query = query;
  35. }
  36.  
  37. //查询全部学生
  38. public List<Student> findAll() {
  39. //初始化查询后封装的数据变量
  40. List<Student> students = null;
  41. //Sql语句
  42. String sql = "select * from student";
  43. //异常处理
  44. try {
  45. //执行sql语句并查询数据
  46. students = query.query(sql, new BeanListHandler<Student>(Student.class));
  47. } catch (SQLException e) {
  48. e.printStackTrace();
  49. }
  50. //返回数据
  51. return students;
  52. }
  53.  
  54. //查询多个学生,根据姓名和地址模糊查询
  55. public List<Student> findByLikeNameAndLikeAddress(String name, String address) {
  56. List<Student> students = null;
  57. String sql = "select * from student where sname like ? and saddress like ? ";
  58. try {
  59. students = query.query(sql, new BeanListHandler<Student>(Student.class), name, address);
  60. } catch (SQLException e) {
  61. e.printStackTrace();
  62. }
  63. return students;
  64. }
  65.  
  66. //查询单个学生根据id
  67. public Student findById(Integer id) {
  68. Student student = null;
  69. try {
  70. student = query.query("select * from student where sid=?", new BeanHandler<Student>(Student.class), id);
  71. } catch (SQLException e) {
  72. e.printStackTrace();
  73. }
  74. return student;
  75. }
  76.  
  77. //查询学生总数
  78. public Integer totalCount() {
  79. Integer total = 0;
  80. try {
  81. total = query.query("select count(sid) from student", new ScalarHandler<Integer>());
  82. } catch (SQLException e) {
  83. e.printStackTrace();
  84. }
  85. return total;
  86. }
  87.  
  88. //添加学生
  89. public Integer add(Student student) {
  90. Integer code = 0;
  91. Object[] obj = {student.getSname(), student.getSsex(), student.getSage(), student.getScredit(),
  92. student.getSmoney(), student.getSaddress(), student.getSenrol()};
  93. String sql = "insert into student (sname,ssex,sage,scredit,smoney,saddress,senrol) values (?,?,?,?,?,?,?) ";
  94. try {
  95. code = query.update(sql, obj);
  96. } catch (SQLException e) {
  97. e.printStackTrace();
  98. }
  99. return code;
  100. }
  101.  
  102. //更新学生
  103. public Integer update(Student student) {
  104. Integer code = 0;
  105. Object[] obj = {student.getSname(), student.getSsex(), student.getSage(), student.getScredit(),
  106. student.getSmoney(), student.getSaddress(), student.getSenrol(), student.getSid()};
  107. String sql = " update student set sname=?,ssex=?,sage=?,scredit=?,smoney=?,saddress=?,senrol=? where sid=? ";
  108. try {
  109. code = query.update(sql, obj);
  110. } catch (SQLException e) {
  111. e.printStackTrace();
  112. }
  113. return code;
  114. }
  115.  
  116. //删除学生
  117. public Integer delete(Integer id) {
  118. Integer code = 0;
  119. try {
  120. code = query.update("delete from student where sid=?", id);
  121. } catch (SQLException e) {
  122. e.printStackTrace();
  123. }
  124. return code;
  125. }
  126. }

Dao接口及实现类

  1. ##### 接口
  2.  
  3. /**
  4. * 学生业务层Service 接口
  5. * @author ant
  6. */
  7. public interface StudentService {
  8. //查询全部学生
  9. List<Student> findAll();
  10. //查询多个学生,根据姓名和地址模糊查询
  11. List<Student> findByLikeNameAndLikeAddress(String name, String address);
  12. //查询单个学生根据id
  13. Student findById(Integer id);
  14. //查询学生总数
  15. Integer totalCount();
  16. //添加学生
  17. void add(Student student);
  18. //更新学生
  19. void update(Student student);
  20. //删除学生
  21. void delete(Integer id);
  22. }
  23.  
  24. +++++++++++++++++++++++++++++++++++++++++
  25.  
  26. ######实现类
  27.  
  28. /**
  29. * 业务接口实现类 学生ServiceStudent
  30. * @author ant
  31. */
  32. public class StudentServiceImpl implements StudentService {
  33.  
  34. //聚合数据操作层
  35. private StudentDao studentDao;
  36. //我们这里使用set方法,方便Spring的注入对象
  37. public void setStudentDao(StudentDao studentDao) {
  38. this.studentDao = studentDao;
  39. }
  40.  
  41. /**
  42. * 注:因为下面的这些数据都是简单的CRUD操作,也没有生命业务逻辑,所以直接调用即可
  43. */
  44. //查询全部学生
  45. public List<Student> findAll() {
  46.  
  47. return studentDao.findAll();
  48. }
  49.  
  50. //查询多个学生,根据姓名和地址模糊查询
  51. public List<Student> findByLikeNameAndLikeAddress(String name, String address) {
  52. return studentDao.findByLikeNameAndLikeAddress(name, address);
  53. }
  54.  
  55. //查询单个学生根据id
  56. public Student findById(Integer id) {
  57. return studentDao.findById(id);
  58. }
  59.  
  60. //查询学生总数
  61. public Integer totalCount() {
  62. return studentDao.totalCount();
  63. }
  64.  
  65. //添加学生
  66. public void add(Student student) {
  67. studentDao.add(student);
  68. }
  69.  
  70. //更新学生
  71. public void update(Student student) {
  72. studentDao.update(student);
  73. }
  74.  
  75. //删除学生
  76. public void delete(Integer id) {
  77. studentDao.delete(id);
  78. }
  79.  
  80. }

Service接口及实现类

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. https://www.springframework.org/schema/beans/spring-beans.xsd">
  6.  
  7. <!--把C3P0连接池放入容器中-->
  8. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  9. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  10. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo_school"></property>
  11. <property name="user" value="root"></property>
  12. <property name="password" value="123"></property>
  13. </bean>
  14.  
  15. <!--注册dbutils里面的QueryRunner对象-->
  16. <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
  17. <constructor-arg name="ds" ref="dataSource"></constructor-arg>
  18. </bean>
  19.  
  20. <!--把StudentDao容器创建出来,使之聚合QueryRunner-->
  21. <bean id="studentDao" class="cn.xw.dao.impl.StudentDaoImpl">
  22. <property name="query" ref="queryRunner"></property>
  23. </bean>
  24.  
  25. <!--把StudentService容器创建出来 并聚合StudentDao对象-->
  26. <bean id="studentService" class="cn.xw.service.impl.StudentServiceImpl">
  27. <property name="studentDao" ref="studentDao"></property>
  28. </bean>
  29. </beans>

最重要的applicationContext.xml配置文件 基于XML的Spring

  1. public class Client {
  2. //ApplicationContext容器
  3. private ApplicationContext app;
  4. //StudentService对象
  5. private StudentService ss;
  6.  
  7. @Before
  8. public void init() {
  9. //初始化
  10. app = new ClassPathXmlApplicationContext("applicationContext.xml");
  11. ss = app.getBean("studentService", StudentService.class);
  12. }
  13.  
  14. @After
  15. public void destroy() {
  16. //这里没有关闭则不写了
  17. }
  18.  
  19. @Test //查询全部测试
  20. public void findAll() {
  21. List<Student> students = ss.findAll();
  22. for (Student student : students) {
  23. System.out.println(student);
  24. }
  25. }
  26.  
  27. @Test //模糊查询测试
  28. public void findByLikeNameAndLikeAddress() {
  29. List<Student> students = ss.findByLikeNameAndLikeAddress("张%", "%六安%");
  30. for (Student student : students) {
  31. System.out.println(student);
  32. }
  33. }
  34.  
  35. @Test //id查找测试
  36. public void findById() {
  37. Student student = ss.findById(16);
  38. System.out.println(student);
  39. }
  40.  
  41. @Test //总数查询测试
  42. public void totalCount() {
  43. Integer total = ss.totalCount();
  44. System.out.println("总数:" + total);
  45. }
  46.  
  47. @Test //添加测试
  48. public void add() {
  49. Student student = new Student(0, "王二虎", "男", 16, 55.5, 600.5, "安徽滁州", "2018-8-8");
  50. ss.add(student);
  51. }
  52.  
  53. @Test //更新测试
  54. public void update() {
  55. Student student = new Student(65, "王小二", "女", 21, 66.5, 666.5, "安徽蚌埠", "2019-8-8");
  56. ss.update(student);
  57. }
  58.  
  59. @Test //删除测试
  60. public void delete() {
  61. ss.delete(65);
  62. }
  63. }

测试

四:Spring之IOC详细介绍(注解版)

1:简单的注解开发框架搭建及测试

首先我来给大家展示一个最简单的注解搭建,后面会一步一步详解,最后会做一个案例,但是看了我下面的简单注解操作会发现很多问题,不是说注解吗?为什么还有配置文件,注入的一下方法就这么点,那注入复杂类型怎么办呢?这里等等问题后面会慢慢解决

  1. ####### pom.xml配置文件
  2. <dependencies>
  3. <!--导入Spring坐标-->
  4. <!--Spring注解开发依赖AOP包-->
  5. <dependency>
  6. <groupId>org.springframework</groupId>
  7. <artifactId>spring-context</artifactId>
  8. <version>5.2.6.RELEASE</version>
  9. </dependency>
  10. <!--单元测试-->
  11. <dependency>
  12. <groupId>junit</groupId>
  13. <artifactId>junit</artifactId>
  14. <version>4.12</version>
  15. </dependency>
  16. </dependencies>
  17.  
  18. ++++++++++++++++++++++++++++++++++++++++++
  19. ##### Dao接口及实现
  20. public interface StudentDao {
  21. //模拟添加学生
  22. void add();
  23. }
  24.  
  25. //这里使用了Repository注解
  26. @Repository(value="studentDao")
  27. public class StudentDaoImpl implements StudentDao {
  28. //模拟添加学生
  29. public void add() {
  30. System.out.println("添加成功");
  31. }
  32. }
  33.  
  34. ++++++++++++++++++++++++++++++++++++++++++
  35. ##### Service接口及实现类
  36. public interface StudentService {
  37. //模拟添加学生
  38. void add();
  39. }
  40.  
  41. //这里使用了Service注解
  42. @Service(value="studentService")
  43. public class StudentServiceImpl implements StudentService {
  44. //这里使用了Autowired依赖注入
  45. //聚合StudentDao对象
  46. @Autowired
  47. private StudentDao studentDao;
  48. //添加学生
  49. public void add() {
  50. studentDao.add();
  51. }
  52. }
  53.  
  54. ++++++++++++++++++++++++++++++++++++++++++
  55. ##### applicationContext.xml配置文件
  56.  
  57. <?xml version="1.0" encoding="UTF-8"?>
  58. <beans xmlns="http://www.springframework.org/schema/beans"
  59. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  60. xmlns:context="http://www.springframework.org/schema/context"
  61. xsi:schemaLocation="http://www.springframework.org/schema/beans
  62. https://www.springframework.org/schema/beans/spring-beans.xsd
  63. http://www.springframework.org/schema/context
  64. https://www.springframework.org/schema/context/spring-context.xsd">
  65.  
  66. <!--加载配置文件后扫描指定文件夹下的注解 -->
  67. <context:component-scan base-package="cn.xw"></context:component-scan>
  68.  
  69. </beans>
  70.  
  71. ++++++++++++++++++++++++++++++++++++++++++
  72. ##### 测试
  73. public class Client {
  74. @Test //添加测试
  75. public void add() {
  76. ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  77. StudentService studentService = app.getBean("studentService", StudentService.class);
  78. studentService.add();
  79. }
  80. }

完成注解的简单操作

2:@Component注解(和XML里面的Bean一样)

  什么是@Component注解呢?大家在写XML的时候是不是使用<bean id="xx" class="xx"></bean>,是说明把指定的对象放入容器中,其实@Component注解也一样,也是告知把指定的对象放入容器中,但是注解比配置的容易,只需要把此注解写在要装入容器对象上即可,说白就是把资源让Spring管理

  1. @Component
  2. public class StudentDaoImpl implements StudentDao{
  3. 内容省略
  4. }
  5. /**
  6. * 我好奇bean标签里面还有id指明以后放入容器取出的key,那这个注解也没有可咋搞?
  7. * 其实如果我们不写默认id是当前类的类名首字母小写 就变成了studentDaoImpl
  8. */
  9. /////////////////////////////////////////////////////////////////////////////
  10. /**
  11. * 默认的id名字太长了,所以我要给注解添加value属性,就和bean里面的id一样
  12. */
  13. @Component(value="studentDao")
  14. public class StudentDaoImpl implements StudentDao{
  15. 内容省略
  16. }
  17. /////////////////////////////////////////////////////////////////////////////
  18. /**
  19. * 其实@Component 是有引申义注解的,为了让注解有个语义性,内部也做了小调整,但整体没太大差异
  20. * @Controller 注解表现层(Servlet)
  21. * @Service 注解业务层(Service)
  22. * @Repository 注解持久层(Dao)
  23. */

  @Controller(value="studentServlet")
  public class StudentServlet{}
  @Service(value="studentService")
  public class StudentServiceImpl implements StudentService{}
  @Repository(value="studentDao")
  public class StudentDaoImpl implements StudentDao{}
  @Component(value="student")
  public class Student{};

3:注解的依赖注入(重要)

①:@Autowired

在注解的入门案例中,大家有发现我使用了@Autowired标签了吗?其实这就是依赖注入标签,使用特别简单,只要在需要注入数据的属性上使用此标签就好了

  1. @Repository(value="studentDao")
  2. public class StudentDaoImpl implements StudentDao{}
  3.  
  4. @Service(value="studentService")
  5. public class StudentServiceImpl implements StudentService{
  6. @Autowired
  7. private StudentDao studentDao;
  8. }
  9. //这样我们就成功把value为studentDao的对象注入进去了 代码片段(1)

上面的一段代码是把StudentDaoImpl对象注入进去了,可是大家发现了吗?我是怎么注入的,@Autowired没有任何标识指向上面的对象,为什么会被注入上呢?那如果我有两个StudentDaoImpl实现类后该直线谁呢?

  1. @Repository(value="studentDaoA")
  2. public class StudentDaoImplA implements StudentDao{}
  3.  
  4. @Repository(value="studentDaoB")
  5. public class StudentDaoImplB implements StudentDao{}
  6.  
  7. @Service(value="studentService")
  8. public class StudentServiceImpl implements StudentService{
  9. @Autowired
  10. private StudentDao studentDao;
  11. }
  12. //那这个又指向谁呢 代码片段(2)

代码片段(1)图   由图证明是可以注入对象的

代码片段(2)图

根据上面2中图的第二张发现,自动注入也会有失败的,原因是多个相同类型的类和属性变量无法区分,因为Spring无法知道你具体要注入哪一个!但是针对第二张图该如何解决呢?其实很简单,只要把属性变量名改为要注入类型的知道key,比如原来是studentDao,可以key容器里面只要studentDaoA和studentDaoB,所以我们自己明确一个即可,但是Spring帮我们解决了这个修改变量名的方式,它为我们提供了一个@Qualified注解

①:@Qualified

@Qualifiend注解就很好的解决了图二的问题,它内部提供value属性,让开发者手动指定对应的key用来匹配,注意,它在注解属性时必须要和@Autowired注解一起使用。

  1. @Repository(value="studentDaoA")
  2. public class StudentDaoImplA implements StudentDao{}
  3.  
  4. @Repository(value="studentDaoB")
  5. public class StudentDaoImplB implements StudentDao{}
  6.  
  7. @Service(value="studentService")
  8. public class StudentServiceImpl implements StudentService{
  9. @Autowired
  10. @Qualifier(value = "studentDaoA")
  11. private StudentDao studentDao;
  12. }

通过上面的标签@Autowired和@Qualified,我们知道,要使用@Qualified注解时必须搭配@Autowird注解,它们2个搭配使用可以完成注入工作,但是你们有想吗?每次都要写这么2个注解太麻烦,没有一个一步到位的标签吗?其实是有的,它就叫@Resource

②:@Resource

这个注解可以说挺容易的,一步到位,我们就简单写一下它吧,然后运行

  1. @Service(value="studentService")
  2. public class StudentServiceImpl implements StudentService {
  3. //聚合StudentDao对象
  4. @Resource(name="studentDao")
  5. private StudentDaoImpl studentDao;
  6. //添加学生
  7. public void add() {
  8. studentDao.add();
  9. }
  10. }

  1. 问题:因为我用的是jdk9版本,而jdk9就已经弃用了这个注解,还有一个和这个相同错误的就是在Spring项目中引入@Resource注解时有红色波浪线
  2. 解决:添加对应被弃用的坐标id
  3. 引申:@Resource这个注解位于java.xml.ws.annotation包是J2EE的一部分,但是J2EEjdk9就被弃用了,并在JDK10删除它,可以通过查询这个包,看到里面的注解
  4. <dependency>
  5. <groupId>javax.annotation</groupId>
  6. <artifactId>javax.annotation-api</artifactId>
  7. <version>1.3.2</version>
  8. </dependency>

 ③:使用set方法注入

我们前3个都是在讲为对象属性注入,而且不用set方法即可注入,那如果要用set注入该如何注入呢?

  1. @Service(value="studentService")
  2. public class StudentServiceImpl implements StudentService {
  3. //聚合StudentDao对象
  4. private StudentDaoImpl studentDao;
  5. //注意:使用set方法注入时在方法参数里面必须指定在容器寻找的key,
  6. //也就是使用@Qualifier注解指示id,这个时候注解可以单独使用,但是在属性对象中必须配合@Autoired注解
  7. //使用set注入数据
  8. public void setStudentDao(@Qualifier(value="studentDao") StudentDaoImpl studentDao) {
  9. this.studentDao = studentDao;
  10. }
  11.  
  12. //添加学生
  13. public void add() {studentDao.add();}
  14. }

④:基本类型注入

基本类型只有8种:int、float、double、char、long、byte、short、boolean,接下来我就争对几个来完成基本类型注入,这里注意的是引用类型只能用上面的3种方法来完成注入,这里针对的是基本类型

  1. //放入Spring容器
  2. @Component(value="myTest")
  3. public class MyTest {
  4.  
  5. //使用Value注解依赖注入
  6. @Value(value="17")
  7. private byte age;
  8. @Value(value="52.6f")
  9. private float weight;
  10. @Value("6000.33")
  11. private double money;
  12. @Value("165")
  13. private int height;
  14. @Value("男")
  15. private char sex;
  16. @Value("true")
  17. private boolean isStudent;
  18.  
  19. //打印语句
  20. @Override
  21. public String toString() {
  22. return "MyTest{" +
  23. "age=" + age +
  24. ", weight=" + weight +
  25. ", money=" + money +
  26. ", height=" + height +
  27. ", sex=" + sex +
  28. ", isStudent=" + isStudent +
  29. '}';
  30. }
  31. }
  32. //测试
  33. class test{
  34. public static void main(String[] args) {
  35. ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  36. MyTest test = (MyTest) app.getBean("myTest");
  37. System.out.println(test);
  38. //MyTest{age=17, weight=52.6, money=6000.33, height=165, sex=男, isStudent=true}
  39. }
  40. }

基本类型注入

4:改变作用范围和生命周期

在前面的xml中介绍了如何改变容器里面的对象的作用范围,默认是单例对象;<bean id="xx" class=“xx.xx.xxx” scope="prototype"></bean>这个就是设置多例的了

可是在注解中如何设置作用范围呢?

  1. @Service(value="studentService")
  2. @Scope(value="singleton")  //这里我设置了单例 但默认不写也是单例 多例是prototype
  3. public class StudentServiceImpl implements StudentService {
  4. ....................
  5. }

既然我们都会设置单例和多例了,可是怎么测试是单例还是多例呢?我就不比较它们的hashCode了,我这么来想,单例对象是根据容器销毁则销毁,而多例对象则由JVM垃圾回收器回收

  1. @Service(value="studentService")
  2. @Scope(value="singleton")
  3. public class StudentServiceImpl implements StudentService {
  4. //聚合StudentDao对象
  5. @Resource(name="studentDao")
  6. private StudentDaoImpl studentDao;
  7.  
  8. //添加学生
  9. public void add() {
  10. studentDao.add();
  11. }
  12.  
  13. //初始化方法
  14. @PostConstruct
  15. public void init(){
  16. System.out.println("初始化成功");
  17. }
  18. //销毁方法
  19. @PreDestroy
  20. public void destroy(){
  21. System.out.println("销毁成功");
  22. }
  23. }
  24.  
  25. ++++++++++++++++++++++++++++++++++++++++++++++
  26. @Test //添加测试
  27. public void add() {
  28. //因为ApplicationContext没有关闭方法,所以我们使用子类
  29. ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  30. StudentService studentService = app.getBean("studentService", StudentService.class);
  31. studentService.add();
  32. //关闭
  33. app.close();
  34. }
  35.  
  36. //使用xml配置方法<bean id="xxx" class="xx.xx.xx" init-method="xx" destroy-method="xxx"></bean>
  37.  
  38. /*其实上面的@PostConstruct 和@PreDestroy 两个注解就相当于init-method="xx"和destroy-method="xxx"标签属性
  39. 但是要注意的是这2个注解和@Resource注解一样必须要导入javax.annotation-api坐标,因为jdk9已经弃用了
  40. 还有的是我们也可以使用初始化方法达到注入属性,不推荐知道就好
  41. //初始化方法
  42. @PostConstruct
  43. public void init(){
  44. studentDao=new StudentDaoImpl();
  45. System.out.println("初始化成功");
  46. }
  47. */

初始化和销毁注解及测试作用范围

5:使用注解替代XML配置文件

 ①:@Configuration和@ComponentScan

我在写注解的基本入门案例中,大家是否记得,我还是用到了xml配置文件,用来告知Spring来开启注解扫描,这显然还是在用xml配置呀,但是接下来的注解中我要彻底消除xml配置文件

  1. /**
  2. * @Configuration 注解说明当前类是一个配置类 和applicationContext.xml一样
  3. */
  4. @Configuration
  5. public class SpringConfig {
  6.  
  7. }

现在我们使用注解@Configuration完成了一个配置类,但是这是一个空配置类,我们要完成注解开发就要对注解扫描,就和使用xml的<context:component-scan base-package="cn.xw"></context:component-scan>一样,那我们就得使用到另一个注解@ComponentScan

  1. /**
  2. * @Configuration 注解说明当前类是一个配置类 和applicationContext.xml一样
  3. */
  4. @Configuration
  5. //推荐使用前五个扫描路径,其实这5个都是一样的 写法不同
  6. @ComponentScan("cn.xw")
  7. //@ComponentScan(value="cn.xw")
  8. //@ComponentScan(value={"cn.xw"})
  9. //@ComponentScan(basePackages = "cn.xw")
  10. //@ComponentScan(basePackages = {"cn.xw"})
  11.  
  12. //扫描类的class文件 不推荐 没有扫描包方便
  13. //@ComponentScan(basePackageClasses ={StudentDaoImpl.class, StudentServiceImpl.class} )
  14.  
  15. //设置多个路径
  16. // @ComponentScans(value={
  17. // @ComponentScan(value="cn.xw"),
  18. // @ComponentScan(value="xxx.xxx.x"),
  19. // @ComponentScan("xxx.xx.xx")
  20. // })
  21. public class SpringConfig {
  22.  
  23. }
  24. /**
  25. * 用于设置单个路径 @ComponentScan
  26. * 用于设置多个路径 @ComponentScans
  27. * 在查询@ComponentScan方法发现value和basePackages是一样的,为什么呢?看下面
  28. * @AliasFor("basePackages")
  29. * String[] value() default {};
  30. * @AliasFor("value")
  31. * String[] basePackages() default {};
  32. * @AliasFor注解在相互引用这2个方法
  33. */

@ComponentScan注解详解

6:@Bean注解的使用

  什么是@Bean注解呢?它有什么用呢?我先来举个例子,比如我们自己写的StudentDaoImpl类如果想放到Spring容器怎么办呢?其实很容易,在StudentDaoImpl类上添加一个@Repository(value="studentDao")就可以了,那么问题来了,我现在有Date、SimpleDateFormat、String三个类都想放到Spring容器中,那么大家的第一反应是直接在那个类上面添加一个注解放入Spring容器中就可以啦,但是大家想想,这3个类不是我们自己的,都是jdk提供的,而且还是class文件,我们是无法修改的,所以Spring就为我们提供了一个@Bean注解用来把初始化好的对象放入容器中,下面我就带大家看看把

  现在有个需求,要求创建一个Date对象并初始化放入容器中,SimpleDateFormat也是一样初始化好格式放入容器,最后在创建一个Spring对象返回一个格式化好的Date日期返回

  1. @Configuration
  2. @ComponentScan("cn.xw")
  3. public class SpringConfig {
  4.  
  5. //创建一个Date对象并放入容器中 key指定为date
  6. @Bean(value="date")
  7. public Date createDate() {
  8. Date date = new Date(12564875956213L);
  9. return date;
  10. }
  11.  
  12. //创建一个SimpleDateFormat对象放入容器中 key指示为simpleDateFormat
  13. @Bean(value = "simpleDateFormat")
  14. public SimpleDateFormat createFormat() {
  15. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
  16. return format;
  17. }
  18.  
  19. //创建一个String对象放入容器 指定key为string
  20. //这里的方法有2个参数,具体是怎么映射上的后面说
  21. @Bean(value = "string")
  22. public String createDateString(Date time,SimpleDateFormat format){
  23. String dateString = format.format(time);
  24. return dateString;
  25. }
  26. }
  27.  
  28. +++++++++++++++++++++++++++++++++++++++++
  29. @Test //添加测试
  30. public void add() {
  31. ApplicationContext app=new AnnotationConfigApplicationContext(SpringConfig.class);
  32. String string = app.getBean("string", String.class);
  33. System.out.println(string); //打印结果:2368-03-02 03-19-16
  34.  
  35. }

@Bean注解解释

注意细节:@Bean注解属性可以写name或者value,因为它们2个互相引用,执行效果都是一样的,用来标识放入IOC容器的id的key值,那么不写name或者value属性的话 默认方法名就为bean的id。

通过@Bean的介绍有个初步的了解,回到上个代码,可看出createDateString(Date time,SimpleDateFormat format)方法要求接收2个参数,可是我在上面也没指示怎么就被自动注入上了呢?其实这个原理和@Autowired自动注入一样的

  1. @Configuration
  2. @ComponentScan("cn.xw")
  3. public class SpringConfig {
  4.  
  5. //创建一个Date对象并放入容器中 key指定为date
  6. @Bean(value="date")
  7. public Date createDate() {
  8. Date date = new Date(12564875956213L);
  9. return date;
  10. }
  11. //创建一个SimpleDateFormat对象放入容器中 key指示为simpleDateFormatA
  12. @Bean(value = "simpleDateFormatA")
  13. public SimpleDateFormat createFormatA() {
  14. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
  15. return format;
  16. }
  17.  
  18. //创建一个SimpleDateFormat对象放入容器中 key指示为simpleDateFormatB
  19. @Bean(value = "simpleDateFormatB")
  20. public SimpleDateFormat createFormatB() {
  21. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  22. return format;
  23. }
  24.  
  25. //创建一个String对象放入容器 指定key为string
  26. //这里的方法有2个参数,具体是怎么映射上的后面说
  27. @Bean(value = "string")
  28. public String createDateString(Date time,@Qualifier("simpleDateFormatB") SimpleDateFormat format){
  29. String dateString = format.format(time);
  30. return dateString;
  31. }
  32. }
  33.  
  34. //方法参数自动注入和属性自动注入一样,假设现在的IOC容器中只要一个SimpleDateFormat类型的,那么Spring也是很
  35. //智能的,直接把那个注入进去即可,因为不可能出现注入错误,但是出现两个相同类型的,Spring就没这么智能了,
  36. //他要我们开发者告知它准确指向
  37.  
  38. //从上面的代码可以看出创建了两个SimpleDateFormat引用类型,我们就可以通过@Qualifier来指定,
  39. //用法在数据注入详细介绍过

7:获取注解容器

  细心的人肯定会发现 我在去除ApplicationContext.xml配置文件后的测试类都使用了AnnotationConfigApplicationContext,原因是现在配置文件都是注解的了,再使用ClassPathXmlApplicationContext就获取不到指定的配置类了,下面我给大家介绍一下

  1. @Test //添加测试
  2. public void add() {
  3. //获取注解类
  4. ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
  5. String string = app.getBean("string", String.class);
  6. System.out.println(string);
  7. /**
  8. * ApplicationContext常见的获取容器子类有3个 在ApplicationContext接口的实现类有介绍前2个
  9. * AnnotationConfigApplicationContext:用来加载读取配置类,用来读取注解配置类、
  10. * 参数可以是伪数组
  11. */
  12. }

获取规则(重要):如果参数直接写到指定的配置类上的class,那个类可以不需要指定@Configuration注解,如果多个类都指定@Configuration注解,那么在获取这些配置类的时候要把全部的class类通过伪数组放入方法参数中。如果配置类过多可以在指定一个主配置类上面标注@Configuration注解,其它的子类可以不指定@Configuration注解,但是在主配置类上要使用@Import注解来引用子配置类。

  1. //主配置类 引用l子配置类
  2. @Configuration
  3. @ComponentScan("cn.xw")
  4. @Import(value={SpringConfigB.class,SpringConfigD.class})
  5. public class SpringConfig {
  6.  
  7. }
  8. //子配置类
  9. class SpringConfigB{}
  10. //子配置类
  11. class SpringConfigD{}

8:获取配置文件数据

配置数据文件我相信大家在写连接数据库的四大数据了经常用到,可是在注解中怎么获取配置连接数据呢?,接下来我就为大家来演示一个常用的操作

  1. <!--Mysql驱动坐标-->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.30</version>
  6. </dependency>
  7. <!--C3P0连接池坐标-->
  8. <dependency>
  9. <groupId>c3p0</groupId>
  10. <artifactId>c3p0</artifactId>
  11. <version>0.9.1.2</version>
  12. </dependency>

导入2个坐标

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/demo_school
  3. jdbc.username=root
  4. jdbc.password=123

dataSource.properties配置文件

  1. @Configuration
  2. @ComponentScan("cn.xw")
  3. @PropertySource("classpath:dataSource.properties")
  4. public class SpringConfig {
  5.  
  6. //注入下面4个属性 单个value可以省去直接写值
  7. @Value(value = "${jdbc.driver}")
  8. private String driver;
  9. @Value(value = "${jdbc.url}")
  10. private String url;
  11. @Value("${jdbc.username}")
  12. private String username;
  13. @Value("${jdbc.password}")
  14. private String password;
  15.  
  16. @Bean(value="dataSource")
  17. public DataSource createDataSourcePool() {
  18. //创建C3P0连接池
  19. ComboPooledDataSource ds = new ComboPooledDataSource();
  20. try {
  21. //设置连接池
  22. ds.setDriverClass(driver);
  23. ds.setJdbcUrl(url);
  24. ds.setUser(username);
  25. ds.setPassword(password);
  26. } catch (PropertyVetoException e) {
  27. e.printStackTrace();
  28. }
  29. return ds;
  30. }
  31. }

注:@PropertySource注解是配置类路径下文件,还有一个@PropertySources注解是配置多个,里面可以写多个@PropertySource,和@ComponentScans一样写法格式

9:Spring整合Junit测试(重要)

我们在前面的时候写测试类都是使用ApplicationContext app=new xxxx(xxx);这样的写法无疑使程序测试变的麻烦,那我们就不能对对属性进行注入然后运行吗,就像下面的这段代码操作

  1. public class Client {
  2. //属性注入
  3. @Autowired
  4. @Qualifier(value = "studentService")
  5. private StudentService ss;
  6.  
  7. @Test //添加测试
  8. public void add() {
  9. //调用保存方法
  10. ss.add();
  11. }
  12. }

  大家看上面的一段代码也没什么错,正常的注入,然后调用Service方法,可是程序在运行的时候抛了一个空指针异常,而且还是明确在ss.add()这一行,那就说明了StudentService属性压根就没有注入上,为什么呢?你们首先想一想,我之前在运行测试的时候会执行到ApplicationContext app=new xxx(xxx),这句话一执行就会找到那个配置文件/配置类,然后读取那个配置文件后,把读取到的数据放到一个IOC容器中,这样我们在后面使用依赖注入的时候就可以去IOC容器取到相对于的类型,可是现在我们把那个ApplicationContext app=new xxx(xxxx)去除了,肯定就找不到了,那么怎么办呢?其实我们需要的是程序能为我们自动创建容器,一旦程序可以自动帮我们创建了容器,那么我们的问题也就解决了。

  其实junit是无法实现帮我们自动创建IOC容器的,因为它的管理范畴就是单单的测试,而且它压根也就不知道你使用的是Spring框架,更别说创建容器了,但是好在junit为外界提供了一个注解,可以让我们指定替换掉它的运行器,这时候我们就要把Spring框架的test的jar包里的SpringJUnit4ClassRunner类放入到运行器中替换,这样就完成了有Spring管理junit了。

  1. <!--Spring的测试坐标-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-test</artifactId>
  5. <version>5.2.6.RELEASE</version>
  6. </dependency>
  7. <!--单元测试-->
  8. <dependency>
  9. <groupId>junit</groupId>
  10. <artifactId>junit</artifactId>
  11. <version>4.12</version>
  12. </dependency>
  13.  
  14. <!--maven导入Spring-test坐标必须要导入junit坐标,而且导入Spring-test坐标的话,junit坐标必须为4.1.2或以上-->

导入对应坐标

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class) //用于指示注解类位置
  3. //@ContextConfiguration(locations = "classpath:applicationContext.xml") //用于指示配置文件为了 类路径下
  4. public class Client {
  5. //属性注入
  6. @Autowired
  7. @Qualifier(value = "studentService")
  8. private StudentService ss;
  9.  
  10. @Test //添加测试
  11. public void add() {
  12. //调用保存方法
  13. ss.add();
  14. }
  15. }
  16. /**
  17. * @RunWith(SpringJUnit4ClassRunner.class)
  18. * 更改运行器,交由Spring管理Junit
  19. *
  20. * @ContextConfiguration(classes = SpringConfig.class)
  21. * 告知Spring我们的配置文件/配置类放到哪了
  22. */

10:注解开发总结案例对学生单表CRUD操作

在学习完前面的注解知识后,我接下来就带大家完成一个纯注解的CRUD操作,还是和XML的总结案例一样,也是那几个技术,mysql建表语句也是和之前的一样。

  1. <dependencies>
  2. <!--mysql驱动坐标-->
  3. <dependency>
  4. <groupId>mysql</groupId>
  5. <artifactId>mysql-connector-java</artifactId>
  6. <version>5.1.32</version>
  7. </dependency>
  8.  
  9. <!--c3p0连接池坐标-->
  10. <dependency>
  11. <groupId>c3p0</groupId>
  12. <artifactId>c3p0</artifactId>
  13. <version>0.9.1.2</version>
  14. </dependency>
  15.  
  16. <!--dbutils工具类坐标-->
  17. <dependency>
  18. <groupId>commons-dbutils</groupId>
  19. <artifactId>commons-dbutils</artifactId>
  20. <version>1.7</version>
  21. </dependency>
  22.  
  23. <!--junit单元测试坐标-->
  24. <dependency>
  25. <groupId>junit</groupId>
  26. <artifactId>junit</artifactId>
  27. <version>4.12</version>
  28. </dependency>
  29.  
  30. <!--Spring-context主要坐标-->
  31. <dependency>
  32. <groupId>org.springframework</groupId>
  33. <artifactId>spring-context</artifactId>
  34. <version>5.2.6.RELEASE</version>
  35. </dependency>
  36.  
  37. <!--Spring-test测试坐标-->
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-test</artifactId>
  41. <version>5.2.6.RELEASE</version>
  42. </dependency>
  43.  
  44. <!--annotation坐标-->
  45. <dependency>
  46. <groupId>javax.annotation</groupId>
  47. <artifactId>javax.annotation-api</artifactId>
  48. <version>1.3.2</version>
  49. </dependency>
  50. </dependencies>

pom.xml坐标文件

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/demo_school
  3. jdbc.username=root
  4. jdbc.password=123

jdbc.properties数据库连接资源文件

  1. public class Student {
  2.  
  3. private int sid; //主键id
  4. private String sname; //姓名
  5. private String ssex; //性别
  6. private int sage; //年龄
  7. private double scredit; //学分
  8. private double smoney; //零花钱
  9. private String saddress; //住址
  10. private String senrol; //入学时间
  11. //因为简单的单表CRUD就不涉及到外键
  12. //private int fid; //外键 连接家庭表信息学生对家庭,一对一
  13. //private int tid; //外键 连接老师信息 学生对老师,一对一
  14. //创建构造器/get/set/toString就不展示了
  15. }

Student实体类

  1. //当前是主配置类
  2. @Configuration
  3. @ComponentScan(value = "cn.xw")
  4. @Import(value={DataSourceConfig.class})
  5. public class SpringConfig {
  6.  
  7. //创建对象QueryRunner放入IOC容器 因为连接QueryRunner有多个操作 所以设置多例
  8. @Bean("queryRunner")
  9. @Scope(value = "prototype")
  10. public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource) {
  11. QueryRunner queryRunner=new QueryRunner(dataSource);
  12. return queryRunner;
  13. }
  14. }
  15.  
  16. +++++++++++++++++++++++++++++++++++++++++
  17.  
  18. //获取配置文件注解
  19. @PropertySource("classpath:jdbc.properties")
  20. public class DataSourceConfig {
  21.  
  22. //注入数据从配置文件获取四大数据
  23. @Value("${jdbc.driver}")
  24. private String driver;
  25. @Value("${jdbc.url}")
  26. private String url;
  27. @Value("${jdbc.username}")
  28. private String username;
  29. @Value("${jdbc.password}")
  30. private String password;
  31.  
  32. //创建c3p0连接池并返回一个DataSource
  33. @Bean("dataSource")
  34. public DataSource createDataSource() {
  35. ComboPooledDataSource ds = new ComboPooledDataSource();
  36. try {
  37. ds.setDriverClass(driver);
  38. ds.setJdbcUrl(url);
  39. ds.setUser(username);
  40. ds.setPassword(password);
  41. } catch (PropertyVetoException e) {
  42. e.printStackTrace();
  43. }
  44. return ds;
  45. }
  46. }

配置类两个(其中一个主配置类)

  1. /**
  2. * 学生数据操作Dao接口
  3. * @author ant
  4. */
  5. public interface StudentDao {
  6. //查询全部学生
  7. List<Student> findAll();
  8. //查询多个学生,根据姓名和地址模糊查询
  9. List<Student> findByLikeNameAndLikeAddress(String name, String address);
  10. //查询单个学生根据id
  11. Student findById(Integer id);
  12. //查询学生总数
  13. Integer totalCount();
  14. //添加学生
  15. Integer add(Student student);
  16. //更新学生
  17. Integer update(Student student);
  18. //删除学生
  19. Integer delete(Integer id);
  20. }
  21.  
  22. +++++++++++++++++++++++++++++++++++++++++
  23.  
  24. /**
  25. * 学生数据操作Dao实现类
  26. * @author ant
  27. */
  28. @Repository("studentDao")
  29. public class StudentDaoImpl implements StudentDao {
  30. //聚合dbutils工具类
  31. @Resource(name = "queryRunner")
  32. private QueryRunner query;
  33.  
  34. //查询全部学生
  35. public List<Student> findAll() {
  36. //初始化查询后封装的数据变量
  37. List<Student> students = null;
  38. //Sql语句
  39. String sql = "select * from student";
  40. //异常处理
  41. try {
  42. //执行sql语句并查询数据
  43. students = query.query(sql, new BeanListHandler<Student>(Student.class));
  44. } catch (SQLException e) {
  45. e.printStackTrace();
  46. }
  47. //返回数据
  48. return students;
  49. }
  50.  
  51. //查询多个学生,根据姓名和地址模糊查询
  52. public List<Student> findByLikeNameAndLikeAddress(String name, String address) {
  53. List<Student> students = null;
  54. String sql = "select * from student where sname like ? and saddress like ? ";
  55. try {
  56. students = query.query(sql, new BeanListHandler<Student>(Student.class), name, address);
  57. } catch (SQLException e) {
  58. e.printStackTrace();
  59. }
  60. return students;
  61. }
  62.  
  63. //查询单个学生根据id
  64. public Student findById(Integer id) {
  65. Student student = null;
  66. try {
  67. student = query.query("select * from student where sid=?", new BeanHandler<Student>(Student.class), id);
  68. } catch (SQLException e) {
  69. e.printStackTrace();
  70. }
  71. return student;
  72. }
  73. //查询学生总数
  74. public Integer totalCount() {
  75. Integer total = 0;
  76. try {
  77. total = Integer.parseInt(query.query("select count(sid) from student", new ScalarHandler<Object>()).toString());
  78. } catch (SQLException e) {
  79. e.printStackTrace();
  80. }
  81. return total;
  82. }
  83. //添加学生
  84. public Integer add(Student student) {
  85. Integer code = 0;
  86. Object[] obj = {student.getSname(), student.getSsex(), student.getSage(), student.getScredit(),
  87. student.getSmoney(), student.getSaddress(), student.getSenrol()};
  88. String sql = "insert into student (sname,ssex,sage,scredit,smoney,saddress,senrol) values (?,?,?,?,?,?,?) ";
  89. try {
  90. code = query.update(sql, obj);
  91. } catch (SQLException e) {
  92. e.printStackTrace();
  93. }
  94. return code;
  95. }
  96. //更新学生
  97. public Integer update(Student student) {
  98. Integer code = 0;
  99. Object[] obj = {student.getSname(), student.getSsex(), student.getSage(), student.getScredit(),
  100. student.getSmoney(), student.getSaddress(), student.getSenrol(), student.getSid()};
  101. String sql = " update student set sname=?,ssex=?,sage=?,scredit=?,smoney=?,saddress=?,senrol=? where sid=? ";
  102. try {
  103. code = query.update(sql, obj);
  104. } catch (SQLException e) {
  105. e.printStackTrace();
  106. }
  107. return code;
  108. }
  109. //删除学生
  110. public Integer delete(Integer id) {
  111. Integer code = 0;
  112. try {
  113. code = query.update("delete from student where sid=?", id);
  114. } catch (SQLException e) {
  115. e.printStackTrace();
  116. }
  117. return code;
  118. }
  119. }

dao数据操作接口及实现类

  1. /**
  2. * 学生业务层Service 接口
  3. * @author ant
  4. */
  5. public interface StudentService {
  6. //查询全部学生
  7. List<Student> findAll();
  8. //查询多个学生,根据姓名和地址模糊查询
  9. List<Student> findByLikeNameAndLikeAddress(String name, String address);
  10. //查询单个学生根据id
  11. Student findById(Integer id);
  12. //查询学生总数
  13. Integer totalCount();
  14. //添加学生
  15. void add(Student student);
  16. //更新学生
  17. void update(Student student);
  18. //删除学生
  19. void delete(Integer id);
  20. }
  21.  
  22. +++++++++++++++++++++++++++++++++++++++++
  23.  
  24. /**
  25. * 业务接口实现类 学生ServiceStudent
  26. * @author ant
  27. */
  28. @Service("studentService")
  29. public class StudentServiceImpl implements StudentService {
  30. //聚合数据操作层
  31. @Autowired
  32. @Qualifier("studentDao")
  33. private StudentDao studentDao;
  34.  
  35. /**
  36. * 注:因为下面的这些数据都是简单的CRUD操作,也没有生命业务逻辑,所以直接调用即可
  37. */
  38. //查询全部学生
  39. public List<Student> findAll() {
  40. return studentDao.findAll();
  41. }
  42. //查询多个学生,根据姓名和地址模糊查询
  43. public List<Student> findByLikeNameAndLikeAddress(String name, String address) {
  44. return studentDao.findByLikeNameAndLikeAddress(name, address);
  45. }
  46. //查询单个学生根据id
  47. public Student findById(Integer id) {
  48. return studentDao.findById(id);
  49. }
  50. //查询学生总数
  51. public Integer totalCount() {
  52. return studentDao.totalCount();
  53. }
  54. //添加学生
  55. public void add(Student student) {
  56. studentDao.add(student);
  57. }
  58. //更新学生
  59. public void update(Student student) {
  60. studentDao.update(student);
  61. }
  62. //删除学生
  63. public void delete(Integer id) {
  64. studentDao.delete(id);
  65. }
  66. }

service业务处理接口级实现类

  1. //设置运行器和配置类位置
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. @ContextConfiguration(classes = SpringConfig.class)
  4. public class Client {
  5. //注解注入
  6. @Autowired
  7. @Qualifier(value="studentService")
  8. private StudentService ss;
  9.  
  10. @Test //查询全部测试
  11. public void findAll() {
  12. List<Student> students = ss.findAll();
  13. for (Student student : students) {
  14. System.out.println(student);
  15. }
  16. }
  17. @Test //模糊查询测试
  18. public void findByLikeNameAndLikeAddress() {
  19. List<Student> students = ss.findByLikeNameAndLikeAddress("张%", "%六安%");
  20. for (Student student : students) {
  21. System.out.println(student);
  22. }
  23. }
  24. @Test //id查找测试
  25. public void findById() {
  26. Student student = ss.findById(16);
  27. System.out.println(student);
  28. }
  29. @Test //总数查询测试
  30. public void totalCount() {
  31. Integer total = ss.totalCount();
  32. System.out.println("总数:" + total);
  33. }
  34. @Test //添加测试
  35. public void add() {
  36. Student student = new Student(0, "王二虎", "男", 16, 55.5, 600.5, "安徽滁州", "2018-8-8");
  37. ss.add(student);
  38. }
  39. @Test //更新测试
  40. public void update() {
  41. Student student = new Student(65, "王小二", "女", 21, 66.5, 666.5, "安徽蚌埠", "2019-8-8");
  42. ss.update(student);
  43. }
  44. @Test //删除测试
  45. public void delete() {
  46. ss.delete(65);
  47. }
  48. }

测试类 Spring整合Junit

五:Spring IOC 总结

  在学了上面的Spring IOC后,知道了Spring IOC为了程序解耦,使用过XML和注解两种方法完成表的CRUD操作,可是这个两个有什么优势呢?或者说哪个更好呢?其实2个都差不多,xml配置是文件更清晰可见,但是特别繁琐,一大段一大段的标签要写,好多都是重复性的写标签,但是注解开发呢,使效率上有提高,但是呢,如果大量的使用注解后使程序的可读性变差;比如在类上面使用注解,使之放到IOC容器中,这样如果出现多个类后,后期要查看当前类是否有放入容器中,只要点卡此类查看,但是使用xml呢?我直接新建一个xml专门存放要存放容器的对象,这样清晰可读,所以总结一下使用注解和xml搭配使用会有好的效果!

Spring IOC 概念及作用的更多相关文章

  1. Spring之旅第二篇-Spring IOC概念及原理分析

    一.IOC概念 上一篇已经了解了spring的相关概念,并且创建了一个Spring项目.spring中有最重要的两个概念:IOC和AOP,我们先从IOC入手. IOC全称Inversion of Co ...

  2. Spring AOP概念及作用

    一:SpringAOP概念 面向切面编程(Aspect Oriented Programming)提高了另一种角度来思考程序的结构,通过预编译方式和运行期间的动态代理实现程序功能的统一维护的一种技术. ...

  3. Spring 学习——Spring IOC概念

    Spring IOC 接口及面向接口编程 接口 定义及理解:接口是一个类的抽象声明,用于由内部操作分离出外部沟通的方式,使其内部进行修改而不影响其外部连接沟通的一种交互方式.不对外公开逻辑处理,只是返 ...

  4. 攻城狮在路上(贰) Spring(二)--- Spring IoC概念介绍

    一.IoC的概念: IoC(控制反转)是Spring容器的核心.另一种解释是DI(依赖注入),即让调用类对某一个接口的依赖关系由第三方注入,以移除调用类对某一个接口实现类的一览. 定义如此,由此可见, ...

  5. 01.Spring Ioc 容器

    基本概念 Spring 的 Ioc 容器,通常也称应用上下文.它包含了两个概念 Ioc 和 容器: 容器:顾名思义就是用来装东西的,在 Spring 中容器里盛放的就是各种各样的 Bean.既然装了东 ...

  6. Spring IOC 原理深层解析

    1 Spring IOC概念认识 1.1 区别IOC与DI 首先我们要知道IOC(Inverse of Control:控制反转)是一种设计思想,就是 将原本在程序中手动创建对象的控制权,交由Spri ...

  7. 自己动手编写spring IOC源码

    前言:对于spring IOC概念不是很了解的朋友可以阅读我上一篇博客--轻松理解spring IOC(这两篇博客也是由于我的个人原因导致现在才发布,惭愧啊).通过这篇博客的理解之后,相信大家会对sp ...

  8. Spring ——Spring IoC容器详解(图示)

    1.1 Spring IoC容器 从昨天的例子当中我们已经知道spring IoC容器的作用,它可以容纳我们所开发的各种Bean.并且我们可以从中获取各种发布在Spring IoC容器里的Bean,并 ...

  9. Spring IoC详解

    Spring IoC详解 1. 控制反转 控制反转是一种通过描述(XML或者注解)并通过第三方去产生或获取特定对象的方式.在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Depend ...

随机推荐

  1. docker 垃圾回收机制

    docker垃圾回收机制 作者: 张首富 时间: 2019-04-10 个人博客: www.zhangshoufu.com QQ群: 895291458 说明 对于Docker来说,存在镜像/容器/存 ...

  2. GitHub使用SSH连接以及生成修改添加密钥详细过程

    目录 1. 先看看本地有没有SSH密钥 2. 生成/修改密钥 3. 把SSH密钥添加到ssh-agent 4. 把SSH密钥添加到GitHub账户里 5. 测试使用ssh地址clone仓库 6. 把远 ...

  3. 敏捷为什么会失败之「PA-SA-WAKA-DA」理论

    在日常生活中,有种有趣的现象:我们更津津乐道于美好的故事,比如提到好莱坞,我们关注的只是大牌明星,却忽略了他们成名其背后的艰辛.对于那些成功的敏捷项目,也是如此.在我们见证成功的同时,却忘记了项目团队 ...

  4. DOM的使用

    1. 修改: 3样: 1. 内容: 3个属性: 1. 获取或修改原始HTML片段: 元素.innerHTML 2. 获取或修改纯文本内容: 元素.textContent vs innerHTML 1. ...

  5. MySQL索引及优化(1)存储引擎和底层数据结构

    在昨天的面试中问到了MySQL索引怎么优化(查询很慢怎么办),回答的很不理想,所以今天来总结几篇关于MySQL索引的知识. 1.什么是索引? 首先我们一定要明确什么是索引?我自己的总结就是索引是一种数 ...

  6. 如何在没有core文件的情况下用dmesg+addr2line定位段错误

    前言 在现网环境下,程序奔溃后不一定会留下core文件,原因有很多,比如存储空间不足就是其中一个常见的原因.此时我们只能依据linux记录的错误日志来定位问题. 涉及linux命令 本文涉及以下几条命 ...

  7. mysql 优化(包含sql语句的书写)

    http://blog.chinaunix.net/uid-11640640-id-3426908.html  mysql性能优化-慢查询分析.优化索引和配置 2012-11-30 15:18:42 ...

  8. 接口参数校验(不使用hibernate-validator,规避大量if else)

    引言 编写接口时,常用的参数校验使用hibernate-validator注解+@@Validated注解进行参数校验.当遇到一些特殊场景或需求,需要自己对参数进行手动校验时,会出现以下问题: 不可避 ...

  9. Java——参数传递

    写这篇文章时,其实还是不理解Java中的参数传递只有传值没有传址(传引用).这里引用知乎上大神的讲解来记录一下. 一.基本类型和引用类型 int num = 10; String str = &quo ...

  10. [PHP动态]0001.关于 PHP 7 你必须知道的五件事

    1.今年的计划表已出.PHP 7 时间表 RFC 投票一直通过, PHP 7 将在2015年10月发布.尽管有些延迟,但我们还是很高兴它在今年内发布.PHP 7 详细时间表由此查看. 2.PHP 要上 ...