Spring学习(二)――Spring中的AOP的初步理解(二)

2014-11-24 01:25:28 · 作者: · 浏览: 1
9 System.out.println("我是奥迪车,我在进行打方向盘");
10 }
11 }
复制代码
5. MainTest.java
复制代码
1 public class MainTest {
2 public static void main(String[] args){
3 AuDi audi=new AuDi();
4 Assistant assistant=new Assistant();
5 Person boy =new Person(audi, assistant);
6 boy.driver();
7 }
8 }
复制代码
6. 运行结果
1 您好,你今天开走了奥迪,我已经做了登记
2 我是奥迪车,我在进行挂档
3 我是奥迪车,我在进行踩油门
4 我是奥迪车,我在进行打方向盘
5 您回来了!请把车交给我,我自行入库就可以了
五、 情形二:使用AOP思想的代码
使用了AOP,Person类就不需要关心Assistant类,我们只需要声明Assistant需要做的事情,Person类就不在直接访问Assistant类的方法了。
本篇文章只是在理解AOP的思想,具体在Spring中AOP是怎么做?使用什么方法,以后在进行学习。
1. Person.java
复制代码
1 public class Person {
2 private Car car;
3 public Person(){
4
5 }
6 public Person(Car car){//构造器注入,传入的是car,也就是一个所有车型都必须实现的接口
7 this.car =car;//这里可以响应奥迪,宝马等任何一种车的实现。
8 }//这里Person类没有与任何特定类型的车发生耦合,对于Person来说,任何一种特定的车,只需要实现Car接口即可。具体是哪一种车型,对Person来说无关紧要。
9 public void driver(){
10 car.GuaDang();
11 car.CaiYouMen();
12 car.DaFangXiang();
13 }
14 }
复制代码
2. Assistant.java
复制代码
1 public class Assistant {
2 public void BeforeDepart(){
3 System.out.println("您好,你今天开走了奥迪,我已经做了登记");
4 }
5 public void AfterBack(){
6 System.out.println("您回来了!请把车交给我,我自行入库就可以了");
7 }
8
9 }
复制代码
3. Car.java
1 public interface Car {
2 public abstract void GuaDang();
3 public abstract void CaiYouMen();
4 public abstract void DaFangXiang();
5 }
4. AuDi.java
复制代码
1 public class AuDi implements Car {
2 public void GuaDang(){
3 System.out.println("我是奥迪车,我在进行挂档");
4 }
5 public void CaiYouMen(){
6 System.out.println("我是奥迪车,我在进行踩油门");
7 }
8 public void DaFangXiang(){
9 System.out.println("我是奥迪车,我在进行打方向盘");
10 }
11 }
复制代码
5. cartest.xml
复制代码
1 < xml version="1.0" encoding="UTF-8" >
2
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context-3.0.xsd
10 http://www.springframework.org/schema/aop
11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
12
13
14
15
16
17
18
19
20
21
22
23
24
复制代码
6. MainTest.java
复制代码
1 import org.springframework.context.ApplicationContext;
2 import org.springframework.context.support.ClassPathXmlApplicationContext;
3 public class MainTest {
4 public static void main(String[] args){
5 ApplicationContext context = new ClassPathXmlApplicationContext("cartest.xml");
6 Person boy =(Person) context.getBean("cartest");
7 boy.driver();
8 }
9 }
复制代码
7. 运行结果
1 您好,你今天开走了奥迪,我已经做了登记
2 我是奥迪车,我在进行挂档
3 我是奥迪车,我在进行踩油门
4 我是奥迪车,我在进行打方向盘
5 您回来了!请把车交给我,我自行入库就可以了