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 ...
随机推荐
- 多个div并排不换行
1.所有div的父元素不换行 white-space: nowrap; 2.所有div设置为行内元素 display: inline-block; 基于java记账管理系统[尚学堂·百战程序员]
- SVN限制IP访问
转自:https://www.cnblogs.com/wjlkingwjl/p/4630764.html 需求 SVN是放在公网的,需要特别指定公司的IP才能获取操作. 操作 在安装完Visual S ...
- 开始Swift学习之路
Swift出来好几个月了,除了同事分享点知识外,对swift还真没有去关心过.GitHub上整理的学习Swift资料还是很不错的,目前也推出了电子书和PDF格式. Swift的语法和我们平常开发的语言 ...
- 【MySql】牛客SQL刷题(上)
牛客SQL题目 题目链接:https://www.nowcoder.com/ta/sql 查找最晚入职员工的所有信息 select * from employees where hire_date = ...
- 【DRF框架】版本控制组件
DRF框架提供的版本控制组件 核心代码: version, scheme = self.determine_version(request, *args, **kwargs)req ...
- unity和lua开发游戏常备技能
推荐阅读: 我的CSDN 我的博客园 QQ群:704621321 我的个人博客 一.使用制作滑动列表:使用UILayout做虚拟列表 ui.list = base:findcom(" ...
- python xml文件解析 及生成xml文件
#解析一个database的xml文件 """ <databaselist type="database config"> <dat ...
- 为RIDE创建桌面快捷方式
问题场景:默认情况下,RIDE的图标不是自动创建的,需要手动添加. 解决方法: 在桌面上新建"快捷方式" 目标对象的位置:C:\Python27\python2.exe - ...
- java技术哪些是必学的?
福州seo推广我们接触过java需要的小伙伴们都知道java是一门强大而又复杂的编程语言,现如今在互联网行业,java的身影随处可见,可能刚学习的小伙伴们会被java语言庞大的体系图吓到,不过知识毕竟 ...
- guava字符串工具--------Joiner 根据给定的分隔符把字符串连接到一起
public class JoinerTest { public static void main(String args[]){ //1.将list字符串集合,以,形式转为字符串 List<S ...