寒冷的冬天,一周两节课,掏出买了一年没翻过的《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的更多相关文章

  1. Spring学习随笔(2):Eclipse下Spring环境配置+入门项目

    1 准备工作 (按需下载) Eclipse 下载:http://www.eclipse.org/downloads/eclipse-packages/ : Spring 下载:http://repo. ...

  2. Spring学习之旅(八)Spring 基于AspectJ注解配置的AOP编程工作原理初探

    由小编的上篇博文可以一窥基于AspectJ注解配置的AOP编程实现. 本文一下未贴出的相关代码示例请关注小编的上篇博文<Spring学习之旅(七)基于XML配置与基于AspectJ注解配置的AO ...

  3. Spring学习笔记(1)——初识Spring

    一.Spring是什么       通常说的Spring其实指的是Spring Framework,它是Spring下的一个子项目,Spring围绕Spring Framework这个核心项目开发了大 ...

  4. Spring学习之——手写Mini版Spring源码

    前言 Sping的生态圈已经非常大了,很多时候对Spring的理解都是在会用的阶段,想要理解其设计思想却无从下手.前些天看了某某学院的关于Spring学习的相关视频,有几篇讲到手写Spring源码,感 ...

  5. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  6. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  7. Spring学习8-用MyEclipse搭建SSH框架 Struts Spring Hibernate

    1.new一个web project. 2.右键项目,为项目添加Struts支持. 点击Finish.src目录下多了struts.xml配置文件. 3.使用MyEclipse DataBase Ex ...

  8. Spring学习之旅(四)Spring工作原理再探

    上篇博文对Spring的工作原理做了个大概的介绍,想看的同学请出门左转.今天详细说几点. (一)Spring IoC容器及其实例化与使用 Spring IoC容器负责Bean的实例化.配置和组装工作有 ...

  9. Spring学习笔记(二) 初探Spring

    版权声明 笔记出自<Spring 开发指南>一书. Spring 初探 前面我们简单介绍了 Spring 的基本组件和功能,现在我们来看一个简单示例: Person接口Person接口定义 ...

  10. Spring学习详解(1)——Spring入门详解

    一:spring的基本用法: 1,关于spring容器: spring容器是Spring的核心,该 容器负责管理spring中的java组件, ApplicationContext ctx  = ne ...

随机推荐

  1. 【转载】IIS网站配置不带www域名直接跳转带www的域名

    很多时候为了统一网站入口,需要将不带www的主域名解析到带www的域名记录下,当客户访问不带www的域名网址的时候自动跳转到带www的域名,在IIS Web服务器中可以通过URL重写模块来实现此功能, ...

  2. 转载 AI-Talking 图算法

    https://mp.weixin.qq.com/s/2XRgJr-ydxHA3JxAZ_5HeA 图算法在风控业务的实践 直播行业中有很多业务风控问题,比如说批量注册.刷热度.垃圾信息以及薅羊毛等. ...

  3. 类中变量私有化和调用:__x和getx/setx或者property

    __xx:双前置下划线,子类不可继承属性.方法,父类私有. 详见:https://www.cnblogs.com/andy9468/p/8299448.html 例子1:隐藏数据:私有化后,用get和 ...

  4. python selectors模块实现 IO多路复用机制的上传下载

    import selectorsimport socketimport os,time BASE_DIR = os.path.dirname(os.path.abspath(__file__))''' ...

  5. 前台.cshtml得到session值方法

    方法一 <script> var s="@Session["visitor_name"]"; if(s=="")//解决报错问题 ...

  6. Python——getpass(密码不显示)

    为了用户输入密码时,不被其他人员看到,可以使用getpass模块来将密码以不显示的形式来表达. import getpass pwd = getpass.getpass() #在PyCharm中,运行 ...

  7. c# 克隆来创建对象副本

  8. STM32 LoRaWAN探索板B-L072Z-LRWAN1中文用户手册

    UM2115用户手册 支持LoRaWAN和 LPWAN协议的STM32L0探索套件 前言 B-L072Z-LRWAN1探索套件采用了 Murata公司的CMWX1ZZABZ-091 LoRa模块.该探 ...

  9. WPF 反编译后错误处理

    1. 首先,手动创建一个WPF工程(WpfApplicationReflectorDemo) 2. 把生成的WpfApplicationReflectorDemo.exe 拖到ILSpy里 3.点击 ...

  10. python基础--切片、迭代、列表生成式

    原文地址:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143175684 ...