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 ...
随机推荐
- Canvas 绘制一个像素风电子时钟
想法是在 Canvas 上绘制由小方块组成的数字. 第一步是实现绘制小方块的方法,先画出一个边长为 5 的 10x10 个方块,使用两个 for 循环很简单就能完成. for (let i = 0; ...
- Java 之 字符输入流[Reader]
一.字符输入流 java.io.Reader 抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中. 它定义了字符输入流的基本共性功能方法. public void close() :关 ...
- select加锁分析(Mysql)
[原创]惊!史上最全的select加锁分析(Mysql) 前言 大家在面试中有没遇到面试官问你下面六句Sql的区别呢 select * from table where id = ? select * ...
- python之csv操作
在使用python爬虫时或者其他情况,都会用到csv存储与读取的相关操作,我们在这里就浅谈一下: CSV(Comma-Separated Values)逗号分隔符,也就是每条记录中的值与值之间是用分号 ...
- python编码和解码
一.什么是编码 编码是指信息从一种形式或格式转换为另一种形式或格式的过程. 在计算机中,编码,简而言之,就是将人能够读懂的信息(通常称为明文)转换为计算机能够读懂的信息.众所周知,计算机能够读懂的是高 ...
- 使用ISO文件制作openstack使用的coreOS镜像
OpenStack源码交流群: 538850354 本篇文章是使用coreOS ISO文件手动制作openstack使用的qcow2镜像文件,关于coreOS的介绍,可以看这里 使用服务器:cento ...
- DNS服务——域名解析转发 和 条件转发
前言 有一台Linux机器作为DNS服务器,查看这台机器上的DNS文件,发现指向互联网上的DNS服务器. [root@ziqiang named]# cat /etc/resolv.conf # Ge ...
- C# Get请求携带body
C# get 请求携带body需要用到RestSharp,可以通过NuGet获取,但是只有.NetFramework 4.5+版本支持.通过Postman可以测试并生成C#代码 var client ...
- leetcode-cn上面刷题
https://leetcode-cn.com/problemset/database/ ------------------------------------------------------- ...
- Caused by: java.lang.ClassNotFoundException: org.fusesource.jansi.WindowsAnsiOutputStream
08:23:18,995 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate append ...