目录
4-1 基于注解开发Spring AOP
实例
这个训练素材基础上加入注解
设置依赖
打开xml增加注解设置
这样就不用zaixml中在进行配置了
此注解说明当前对象用于持久化
因为service依赖于dao要对其进行注入
两种注入方式
会将private改为public直接对其赋值
或者采用set方法对这个属性进行设置
userservice同上
新增方法切面类
方法同,如何配置切面类呢?
这样ioc就会对她进行实例化和管理
配置完成
创建springApplication
睡眠三秒
调用
说明aop配置已生效
4-3 自由编程
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--初始化IoC容器-->
<context:component-scan base-package="com.imooc"/>
<!--启用Spring AOP注解模式-->
<aop:aspectj-autoproxy/>
</beans>
package com.imooc.spring.aop.dao;
import org.springframework.stereotype.Repository;
/**
* 书店表dao
*/
@Repository
public class BookShop {
public void sellingBooks(){
System.out.println("卖出一本java基础书籍");
}
}
package com.imooc.spring.aop.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MethodPro {
@Before("execution(* com.imooc..*.*(..))")
public void preSales(){
System.out.println("=========售前服务=========");
}
@After(("execution(* com.imooc..*.*(..))"))
public void afterSale(){
System.out.println("=========售后服务==========");
}
}
package com.imooc.spring.aop;
import com.imooc.spring.aop.dao.BookShop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
BookShop bookShop = context.getBean("bookShop", BookShop.class);
bookShop.sellingBooks();
}
}