Spring学习随笔(1):为什么要使用Spring
寒冷的冬天,一周两节课,掏出买了一年没翻过的《Spring实战》。
刚刚接触spring的我对它还不是很熟悉,对各种知识的认知也比较浅薄,但我会学习的过程通过随笔记录下来,监督自己学下去。
1 依赖注入(DI)
大部分的Spring的新手(我)在学习之初对依赖注入这个词感到迷茫,事实上它并没有那么复杂,应用依赖注入会使得代码变得更简单、更容易理解。
通常,我们开发的java应用都是由多个类组成,它们之间相互协作来完成特定的业务逻辑。每个对象之间相互联系,导致高度耦合的代码。
参考代码:
package com.spring;
public class Performer {
private Violin violin;
public Performer(){
violin=new Violin(); //与Violin紧密耦合
}
public void play(){
violin.play();
}
}
class Violin extends Instrument {
public void play() {
System.out.println("Violin music!");
}
}
class Instrument {
void play(){};
}
上面的代码有个非常明显的问题:Performer在构造函数中创建Violin,这使得Performer与Violin紧密耦合在一起,并且当演奏家需要演奏其他乐器时,就需要改写代码。
参考代码:
package com.spring;
public class Performer {
private Instrument ins;
public Performer(Instrument ins){
this.ins=ins;
}
public void play(){
ins.play();
}
}
class Violin extends Instrument {
public void play() {
System.out.println("Violin music!");
}
}
class Instrument {
void play(){};
}
不同于之前的演奏家,这次的演奏家没有创建乐器,而是通过构造函数将乐器通过构造参数传入。这便是依赖注入的一种:构造器注入。
它不仅能够演奏小提琴,无论是钢琴、大提琴、手风琴等继承了Instrument的子类都能作为参赛传入。
而且它本身并不知道将会演奏什么乐器,这与它无关。这便是依赖注入的好处-------松耦合。
现在performer可以接受任意instrument,那我们如何将instrument传递给它呢(装配)?Spring有多种装配的方式,XML配置是最常用的一种。
在classpath下创建xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="performer" class="com.spring.Performer">
<constructor-arg ref="violin"/>
</bean> <bean id="violin" class="com.spring.Violin"></bean> </beans>
测试是否成功:
package com.spring; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class PerformerMain { public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext apc = new ClassPathXmlApplicationContext("spring.xml");
Performer hello = (Performer) apc.getBean("performer");
hello.play();
} }

2 面向切面编程(AOP)
AOP:允许你把遍布应用各处的功能分离出来形成可重用的组件。
比方说,系统中的日志、事务管理。安全服务等,通常会分散到你的每一个组件中,哪怕只是调用某个方法,但他依然会使你的代码变得混乱并且不易修改。某个组件应该只关心如何实现自身的业务逻辑,与其无关的代码(日志,安全等)应该少出现甚至不出现。

AOP:

AOP使得这些组件具有更高的内聚性以及更加关注与自身业务,完全不需要涉及其他系统服务,甚至你的核心业务根本不知道它们(日志模块,安全模块)的存在。
为了了解Spring中如何使用切面,我依然使用上面的列子。
我们现在需要记录每次演奏开始的时间与结束的时间,通常我们会这么做:
package com.spring; import java.text.SimpleDateFormat;
import java.util.Date; public class Performer {
private Instrument ins;
private Record rec;
public Performer(Instrument ins){
this.ins=ins;
this.rec=new Record();
}
public void play(){
rec.starttime();
ins.play();
rec.endtime();
}
}
class Record{
private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void starttime(){
System.out.println(df.format(new Date()));
}
public void endtime(){
System.out.println(df.format(new Date()));
}
}
从上面的代码我们可以明显的看出,performer应该专心演奏,而不需要去做记录时间这种事情,这使得Performer的代码复杂化。
如何将Record抽象为切面呢?只需要在配置文件中声明就可以了:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
default-autowire="byName"> <bean id="performer" class="com.spring.Performer">
<constructor-arg ref="violin" />
</bean> <bean id="violin" class="com.spring.Violin"></bean>
<bean id="record" class="com.spring.Record"></bean> <aop:config>
<aop:aspect ref="record"> <aop:pointcut expression="execution(* com.spring.Performer.play(..))" id="play"/> <aop:before method="starttime" pointcut-ref="play"/>
<aop:after method="endtime" pointcut-ref="play"/>
</aop:aspect>
</aop:config>
</beans>
package com.spring; import java.text.SimpleDateFormat;
import java.util.Date; public class Performer {
private Instrument ins;
public Performer(Instrument ins){
this.ins=ins; //与Violin紧密耦合
}
public void play(){
ins.play();
}
}
class Record{
private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void starttime(){
System.out.println(df.format(new Date()));
}
public void endtime(){
System.out.println(df.format(new Date()));
}
}
运行结果:

注意:aop除了spring的包外还需要aspectJ框架的包:

Spring学习随笔(1):为什么要使用Spring的更多相关文章
- Spring学习随笔(2):Eclipse下Spring环境配置+入门项目
1 准备工作 (按需下载) Eclipse 下载:http://www.eclipse.org/downloads/eclipse-packages/ : Spring 下载:http://repo. ...
- Spring学习之旅(八)Spring 基于AspectJ注解配置的AOP编程工作原理初探
由小编的上篇博文可以一窥基于AspectJ注解配置的AOP编程实现. 本文一下未贴出的相关代码示例请关注小编的上篇博文<Spring学习之旅(七)基于XML配置与基于AspectJ注解配置的AO ...
- Spring学习笔记(1)——初识Spring
一.Spring是什么 通常说的Spring其实指的是Spring Framework,它是Spring下的一个子项目,Spring围绕Spring Framework这个核心项目开发了大 ...
- Spring学习之——手写Mini版Spring源码
前言 Sping的生态圈已经非常大了,很多时候对Spring的理解都是在会用的阶段,想要理解其设计思想却无从下手.前些天看了某某学院的关于Spring学习的相关视频,有几篇讲到手写Spring源码,感 ...
- 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】
一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...
- 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】
一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...
- Spring学习8-用MyEclipse搭建SSH框架 Struts Spring Hibernate
1.new一个web project. 2.右键项目,为项目添加Struts支持. 点击Finish.src目录下多了struts.xml配置文件. 3.使用MyEclipse DataBase Ex ...
- Spring学习之旅(四)Spring工作原理再探
上篇博文对Spring的工作原理做了个大概的介绍,想看的同学请出门左转.今天详细说几点. (一)Spring IoC容器及其实例化与使用 Spring IoC容器负责Bean的实例化.配置和组装工作有 ...
- Spring学习笔记(二) 初探Spring
版权声明 笔记出自<Spring 开发指南>一书. Spring 初探 前面我们简单介绍了 Spring 的基本组件和功能,现在我们来看一个简单示例: Person接口Person接口定义 ...
- Spring学习详解(1)——Spring入门详解
一:spring的基本用法: 1,关于spring容器: spring容器是Spring的核心,该 容器负责管理spring中的java组件, ApplicationContext ctx = ne ...
随机推荐
- iOS - error:unrecognized selector sent to class 导入第三方SDK .a后不识别,运行崩溃
今天将app统计的.a静态库包含到一个app应用中,调试时报下面的错误: *** Terminating app due to uncaught exception 'NSInvalidArgumen ...
- Vue组件component创建及使用
组件化与模块化的区别 什么是组件:组件的出现,就是为了拆分Vue实例的代码量,能够让我们以不同的组件,来划分不同的功能模块 ,将来我们需要什么功能,就可以去调用对应的组件即可 组件化与模块化的不同: ...
- Linux 之 压缩解压缩
Linux中常见的压缩格式 .zip .gz .bz2 .tar.gz tar.bz2 zip zip格式的压缩文件和win ...
- 【DRF框架】序列化组件——字段验证
单个字段的验证 1.在序列化器里定义校验字段的钩子方法 validate_字段 2.获取字段的数据 3.验证不通过,抛出异常 raise serializers.ValidationError( ...
- MySQL数据库语法-单表查询练习
MySQL数据库语法-单表查询练习 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客主要是对聚合函数和分组的练习. 一.数据表和测试数据准备 /* @author :yinz ...
- 系统间HTTP调用代码封装
痛点 最近接手一个老项目,这个项目几经转手,到我这里时,发现代码的可阅读性实在是很差,对于一个有点代码洁癖的我来说,阅读起来实在是很难受.其中一个痛点,现在就拉出来讲讲.该项目需要与另外一个项目进行业 ...
- 解决在macOS下安装了python却没有pip命令的问题【经验总结】
可以使用brew直接安装python,但是安装完成了之后没有pip命令. pip是常用的python包管理工具,类似于java的maven.第一反应brew install pip,却提示没这货. 可 ...
- CORS通信
CORS 是一个 W3C 标准,全称是"跨域资源共享"(Cross-origin resource sharing).它允许浏览器向跨域的服务器,发出XMLHttpRequest请 ...
- 什么是Log4j,Log4j详解!
由于时间紧急,自己就不写了.一下转载链接: https://www.cnblogs.com/ITtangtang/p/3926665.html
- 2020还有9天!Winforms开发有哪些期待?DevExpress 2020计划出炉
下载DevExpress v19.2完整版 DevExpress Winforms Controls 内置140多个UI控件和库,完美构建流畅.美观且易于使用的应用程序.DevExpress Winf ...