关于Spring的一些笔记

  1 Spring是什么?

  不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。容器(在 Spring 框架中是 IOC 容器) 负责将这些联系在一起。在典型的 IOC 场景中,容器创建了所有对象,并设置必要的属性将它们连接在一起,决定什么时间调用方法。

  具体步骤有:


1、编写业务对象 UserDao UserService

2、配置ApplicationContext.xml

3、实例化Spring IOC

4、通过IOC使用Spring加工过的业务对象

  以一个实例说明:

1 package com.aop2;
2
3 public interface IMessage {
4     public void check();
5 }
 1 package com.aop2;
 2
 3 public class Message implements IMessage {
 4
 5     private String name;
 6
 7     public String getName() {
 8         return name;
 9     }
10
11     public void setName(String name) {
12         this.name = name;
13     }
14
15     public void check() {
16         System.out.println("checking " + name);
17     }
18
19 }

配置beans.xml

 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     xmlns:p="http://www.springframework.org/schema/p"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
 7
 8     <bean id = "message" class = "com.aop2.Message">
 9         <property name = "name" value = "alvin"/>
10     </bean>
11
12 </beans>

添加测试类:

 1 package com.aop2;
 2
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6
 7 public class AopTest {
 8     @Test
 9     public void test() {
10         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
11                 "com/aop2/beans.xml");
12         IMessage message1 = (IMessage)applicationContext.getBean("message");
13         message1.check();
14     }
15 }

输出:checking alvin

  2 通过代理实现

  上述过程并没有使用代理机制,下面使用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     xmlns:p="http://www.springframework.org/schema/p"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
 7
 8     <!-- 配置被代理对象 -->
 9     <bean id = "message" class = "com.aop2.Message">
10         <property name = "name" value = "alvin"/>
11     </bean>
12
13     <!-- 配置代理对象 -->
14     <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
15         <!-- 代理接口集 -->
16         <property name="proxyInterfaces">
17             <list>
18                 <value>com.aop2.IMessage</value>
19             </list>
20         </property>
21
22         <!-- 配置被代理对象 -->
23         <property name="target" ref="message" />
24     </bean>
25
26 </beans>

修改测试类:

package com.aop2;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopTest {
    @Test
    public void test() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "com/aop2/beans.xml");
        IMessage message1 = (IMessage)applicationContext.getBean("proxyFactoryBean");
        message1.check();
    }
}

测试结果:checking alvin

  可以看到,测试结果并没有改变,但是我们在beans.xml配置中把被代理对象message利用IOC机制放入代理对象,实现了控制的反转,在测试类中,我们将不再直接取出message类,而是通过调用动态代理类proxyFactoryBean来调用类,并取得类方法。这就揭示了Spring的思想——解耦。它是的类与类之间的耦合度降低,我们不再类中直接调用相应的方法,而是通过bean容器配置,设置必要属性的方法来使用。

  3 调用多个接口

增加接口:

1 package com.aop2;
2
3 public interface IMessage2 {
4     public void release();
5 }

添加property:

1 <property name="proxyInterfaces">
2     <list>
3         <value>com.aop2.IMessage</value>
4         <value>com.aop2.IMessage2</value>
5     </list>
6 </property>

测试类:

 1 package com.aop2;
 2
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6
 7 public class AopTest {
 8     @Test
 9     public void test() {
10         ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
11                 "com/aop2/beans.xml");
12         IMessage message1 = (IMessage)applicationContext.getBean("proxyFactoryBean");
13         IMessage2 message2 = (IMessage2)applicationContext.getBean("proxyFactoryBean");
14         message1.check();
15         message2.release();
16     }
17 }

测试结果为:

checking alvin
release alvin

  4 AOP

  AOP是在动态代理的基础上实现的,利用InvocationHandler动态代理接口产生一个对象的代理对象,对被代理对象进行代理,以下是动态代理的实质:

 1 public class DaiLi_DongTai {
 2     public static void main(String[] args) {
 3         IGamePlayer player = new GamePlayer("张三");
 4         InvocationHandler handler = new GamePlayIG(player);
 5         System.out.println("开始时间:" + new Date());
 6         ClassLoader cl = player.getClass().getClassLoader();
 7         IGamePlayer proxy = (IGamePlayer) Proxy.newProxyInstance(cl,
 8                 new Class[] { IGamePlayer.class }, handler);
 9         proxy.login("zhagnsan", "password");
10         proxy.killBoss();
11         proxy.upgrade();
12         System.out.println("结束时间:" + new Date());
13     }
14 }
15
16 class GamePlayIG implements InvocationHandler {
17     Class cls = null; //被代理者
18     Object obj = null; //被代理的实例
19     public GamePlayIG(Object obj) {//我要代理谁
20         this.obj = obj;
21     }
22     //调用被代理的方法
23     public Object invoke(Object proxy, Method method, Object[] args)
24             throws Throwable {
25         Object result = method.invoke(this.obj, args);
26         return result;
27     }
28 }

  5 AOP实现

  加入AOP编程,这里以环绕通知为例,在方法执行的前后加入日志程序。

设定MyMethodInterceptor类:

 1 package com.aop2;
 2
 3 import org.aopalliance.intercept.MethodInterceptor;
 4 import org.aopalliance.intercept.MethodInvocation;
 5
 6 public class MyMethodInterceptor implements MethodInterceptor{
 7
 8     public Object invoke(MethodInvocation arg0) throws Throwable {
 9         System.out.println("写入日志...");
10         Object object = arg0.proceed();
11         System.out.println("日志完成...");
12         return object;
13     }
14 }

修改beans.xml配置:

 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     xmlns:p="http://www.springframework.org/schema/p"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
 7
 8     <!-- 配置被代理对象 -->
 9     <bean id = "message" class = "com.aop2.Message">
10         <property name = "name" value = "alvin"/>
11     </bean>
12
13     <!-- 配置环绕通知 -->
14     <bean id = "myMethodInterceptor" class = "com.aop2.MyMethodInterceptor"/>
15
16     <!-- 配置代理对象 -->
17     <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
18         <!-- 代理接口集 -->
19         <property name="proxyInterfaces">
20             <list>
21                 <value>com.aop2.IMessage</value>
22                 <value>com.aop2.IMessage2</value>
23             </list>
24         </property>
25
26         <!-- 织入通知对象 -->
27         <property name = "interceptorNames">
28             <list>
29                 <value>myMethodInterceptor</value>
30             </list>
31         </property>
32
33         <!-- 配置被代理对象 -->
34         <property name="target" ref="message" />
35     </bean>
36
37 </beans>

输出为:

写入日志...
checking alvin
日志完成...
写入日志...
release alvin
日志完成...

可以看到,在执行方法的前后,都有通知织入。

时间: 2024-08-07 21:20:20

关于Spring的一些笔记的相关文章

Spring MVC 学习笔记(二):@RequestMapping用法详解

一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置 <servlet>     <servlet-name>servletName</servlet-name>     <servlet-class>ServletClass</servlet-class> </servlet>

Spring Batch学习笔记二

此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch的架构 一个Batch Job是指一系列有序的Step的集合,它们作为预定义流程的一部分而被执行: Step代表一个自定义的工作单元,它是Job的主要构件块:每一个Step由三部分组成:ItemReader.ItemProcessor.ItemWriter:这三个部分将执行在每一条被处理的记录上,ItemReader读取每一条记录,然后传递给ItemProcessor处理,最后交给ItemWriter做持久化:It

[Spring MVC]学习笔记--DispatcherServlet

在上一篇我们介绍了Servlet,这一篇主要来看一下MVC中用到的DispatcherServlet(继承自HttpServlet). 1. DispatcherServlet在web.xml中被声明. <web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet&l

Spring MVC学习笔记(一)--------准备篇

这一系列笔记将带你一步一步的进入Spring MVC,高手勿喷. 首先你得安装以下的工具: JDK,虽然JDK8已经发布了一段时间了,但是由于我们并不会使用到里面的新特性,所以JDK6以上版本皆可以(需加入到PATH环境变量中): Servlet Container,为了能运行WEB应用程序,因此需要一个Web Container,这里我们建议Tomcat即可: IDE,一个好的IDE不仅能提高你开发的效率,还能降低你学习的成本,我们选择的是IntelliJ: 构建工具,推荐使用Gradle,它

[转]Spring MVC 学习笔记 json格式的输入和输出

Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用 <!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.8.1</version>

Spring Batch学习笔记三:JobRepository

此系列博客皆为学习Spring Batch时的一些笔记: Spring Batch Job在运行时有很多元数据,这些元数据一般会被保存在内存或者数据库中,由于Spring Batch在默认配置是使用HSQLDB,也就是说在Job的运行过程中,所有的元数据都被储存在内存中,在Job结束后会随着进程的结束自动消失:在这里我们推荐配置JobRepository去使用MySQL. 在这种情况下,Spring Batch在单次执行或者从一个执行到另外一个执行的时候会使用数据库去维护状态,Job执行的信息包

Spring视频学习笔记(二)

Spring视频学习笔记(二) XML配置里的Bean自动装配(三个来测试实现) /** * Person类 * */ public class Person { private String name; private Address address; private Car car; public String getName() { return name; } public void setName(String name) { this.name = name; } public Ad

[Spring MVC]学习笔记--基础Servlet

Servlet是一个用Java编写的应用程序,在服务器上运行,处理请求的信息并将其发送到客户端. Servlet的客户端提出请求并获得该请求的响应. 对于所有的客户端请求,只需要创建Servlet的实例一次(这是和CGI(Common Gateway Interface)的重要区别,CGI是每个请求创建一个新实例),因此节省了大量的内存. Servlet在初始化后即驻留内存中,因此每次作出请求时无需加载. 下面通过一个例子来介绍如何编写一个简单的Servlet. 准备工作: 1. 下载并启动To

Spring boot 学习笔记 (二)- 整合MyBatis

Spring boot 学习笔记 (二)- 整合MyBatis Spring Boot中整合MyBatis,并通过注解方式实现映射. 整合MyBatis 以Spring boot 学习笔记 (一)- Hello world 为基础项目,在pom.xml中添加如下依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter&l

spring框架搭建笔记

◆简介 目的:解决企业应用开发的复杂性 功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能 范围:任何Java应用 Spring 框架是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式. 组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现.每个模块的功能如下: ? 核心容器:核心容器提供 Spring 框架的基本功能.核心容器的主要组件是 BeanFac