1、aop之纯java写aop
案例背景:模拟商店卖酒
前期工作:
(1)创建普通java工程,如下是我构建的工程结构,你们根据需要自己创建(我是在test下写案例)
(2)applicationContext.xml是spring的配置文件,目前配置很简单,就一个包扫描,目前配置的意思就是扫描com.wys.service.impl下的类。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.wys.service.impl"></context:component-scan>
</beans>
component-scan是组件扫描,也就是说如果想把某个类实例化后交给spring管理,那么这个包内的类,如果存在@Component注解,那么就会被扫描到,并且把它实例化后放到spring中,如图所示:我在实现类上加了@Component("shop")
package com.wys.service.impl;
import com.wys.service.ShopService;
import org.springframework.stereotype.Component;
/**
* @Author:花季岁月
* @Date Created in 2022/3/28 9:28
* @Description:店铺实现类
*/
@Component("shop")
public class ShopServiceImpl implements ShopService {
@Override
public void saleBeer(Integer money) {
System.out.println("啤酒:" + money + "元");
}
@Override
public void saleSpirit(Integer money) {
try {
System.out.println("白酒:" + money + "元");
} catch (Exception e) {
System.out.println("买白酒异常");
e.printStackTrace();
} finally {
System.out.println("买白酒finally");
}
}
@Override
public int saleRedWine(Integer money) {
System.out.println("红酒:" + money + "元");
return money;
}
}
(3)TestAop类,程序入口,其实就是一个main函数,使用传统的方法来初始化spring容器
package com.wys.test;
import com.wys.service.ShopService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAop {
public static void main(String[] args) {
//通过配置的路劲获取到spring配置文件,得到一个上下文对象ApplicationContext
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xml/applicationContext.xml");
//通过上下文的getBean得到某个组件
ShopService shop = (ShopService) applicationContext.getBean("shop");
//得到组件后 运行该组件中的方法
shop.saleBeer(5);
shop.saleSpirit(10);
shop.saleRedWine(15);
}
}
这里注意下,getBean里面的id值“shop”,我们发现在配置文件中并没有配置这个id,那是怎么获取的呢?细心的同学已经发现了,这里我是直接写在类上@Component("shop")注解中。
(4)接口类ShopService,这里我写了3个方法做测试
package com.wys.service;
/**
* @Author:花季岁月
* @Date Created in 2022/3/28 9:26
* @Description:
*/
public interface ShopService {
//啤酒
public void saleBeer(Integer money);
//白酒
public void saleSpirit(Integer money);
//红酒
public int saleRedWine(Integer money);
}
(5)实现类代码在步骤(2),里面主要是实现接口类的3个方法,这里就简单的做个输出打印信息。
(6)运行TestAop类,结果如下:
至此,前期准备工作已完成。