使用注解配置spring

  1.导入 spring-aop-5.0.6.RELEASE.jar包

  2.为主配置文件引入新的命名空间 xmlns:context="http://www.springframework.org/schema/context"

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-4.0.xsd"> <!--指定扫描com.david.bean下的所有包所有类中的注解 -->
<context:component-scan base-package="com.david.bean"></context:component-scan> </beans>

  3.在类中使用注解

@Component("user")
//相当于<bean name="user" class="com.david.bean.User" />
public class User {
private String name;
private Integer age;
private Car car; ...
}

注解后来又出现了三种,可以体现层级关系

@Component("user")
@Service("user") //service层
@Controller("user") //web层
@Repository("user") //dao层

指定作用范围

@Component("user")
//相当于<bean name="user" class="com.david.bean.User" />
@Scope(scopeName = "prototype")
//相当于<bean name="user" class="com.david.bean.User" scope="prototype"></bean>

值类型注入

public class User {
@Value("david") //字段注入 破坏了封装性
private String name;
private Integer age;
private Car car; @Value("18") //set方法注入 推荐使用
public void setAge(int age) {
this.age = age;
}
...
}

引用类型(对象)注入

@Component("car")
public class Car {
@Value("奥拓")
private String name;
@Value("red")
private String color;
...
}
@Component("user")
public class User {
@Autowired //自动装配 对象注入
private Car car;
...
}

@autowired 自动装配的方式 如果匹配到多个类型一致的对象,无法选择具体注入哪一个对 如:

    <bean name="car2" class="com.david.bean.Car">
<property name="name" value="奥迪"></property>
<property name="color" value="black"></property>
</bean>

此时需要使用@Qualifier("car2")注解告诉容器具体注入哪个对象 和@autowired一起使用

    @Autowired
@Qualifier("car2")
private Car car;

上面这种要使用两个注解,还有一个注解@Resource 可以手动指定注入哪个对象

    @Resource(name="car2") //手动指定
private Car car;

初始化和销毁

public class User {
...
@PostConstruct //相当于init-method 对象创建后调用
public void init(){
System.out.println("init");
} @PreDestroy //销毁前调用 相当于destory-method
public void destory(){
System.out.println("destory");
}
...
}

aop:面向切面编程,是对oop面向对象编程的补充和完善。

spring中的aop

  spring能够为容器中管理的对象生成动态代理对象。

spring实现aop的原理

  1.动态代理(优先使用)

    被代理对象必须要实现接口,才能产生代理对象,如果没有接口将不能使用动态代理技术

  2.cglib代理(没有接口时)

    第三方代理技术,可以对任何类生成代理对象。代理的原理是对目标对象进行继承代理

spring AOP 名词解释:

  1.Joinpoint连接点:目标对象中,所有可以增强的方法。(可以增强的方法)如:UserServiceImpl implements UserService 中实现的方法 save() delete()

  2.Pointcut切入点:目标对象中,已经增强的方法。(已增强的方法)如:已通过代理增强的save() 或delete() 可以单独指定某些增强或不增强。

  3.Advice通知/增强:需要增强的代码。(代理对象调用目标方法前后执行的代码)如://前增强 method.invoke(us,arg) //后增强。

  4.Target目标对象:被代理对象。如UserServiceImpl。

  5.Weaving织入:将通知织入(应用到)切入点的过程。

  6.Proxy代理:将通知织入道目标对象之后,形成代理对象。

所以进行AOP编程的关键就是定义切入点和定义增强处理,一旦定义了合适的切入点和增强处理,AOP框架将自动生成AOP代理,即:代理对象的方法=增强处理+被代理对象的方法。

基于spring的aop实现

1.导包 aopalliance.jar aspectjweaver.jar  spring aop需要这两个包的支持 下载地址:

http://www.java2s.com/Code/Jar/a/Downloadaopalliancejar.htm

http://www.java2s.com/Code/Jar/a/Downloadaspectjweaverjar.htm

2.准备目标对象

  先定义一个接口

public interface IHelloWorld {
void printHelloWorld();
void doPrint();
}

  在定义两个接口实现类

public class HelloWorldImpl1 implements IHelloWorld
{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
} public void doPrint()
{
System.out.println("Enter HelloWorldImpl1.doPrint()");
return ;
}
} public class HelloWorldImpl2 implements IHelloWorld{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
} public void doPrint()
{
System.out.println("Enter HelloWorldImpl2.doPrint()");
return ;
}
}

3.准备通知

package com.david.bean;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
//前置通知-目标方法调用之前调用
public void before() {
System.out.println("前置通知");
} //后置通知-目标方法之后调用,如果异常不会调用
public void afterRuning() {
System.out.println("后置通知,出现异常不会调用");
} //环绕通知-在目标方法之前和之后都调用
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前通知");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("环绕后通知");
} //异常通知-如果出现异常就会被调用
public void afterException(){
System.out.println("出现异常");
} //后置通知-目标方法之后调用,无论异常与否都会调用
public void after() {
System.out.println("后置通知,无论异常与否都会调用");
}
}

4.配置进行织入,将通知织入目标对象中

新建一个aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--导入aop命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--配置目标对象 -->
<bean id="helloWorldImpl1" class="com.david.bean.HelloWorldImpl1" />
<bean id="helloWorldImpl2" class="com.david.bean.HelloWorldImpl2" />
<!--配置通知对象 -->
<bean id="myAdvice" class="com.david.bean.MyAdvice" />
<!--配置将通知织入目标对象 -->
<aop:config>
<!--配置切入点:所有方法都增强 -->
<aop:pointcut id="allMethod" expression="execution(* com.david.bean.IHelloWorld.*(..))"></aop:pointcut>
<aop:aspect id="advice" ref="myAdvice">
<!--通知方法 -->
<aop:before method="before" pointcut-ref="allMethod" />
<aop:after-returning method="afterRuning" pointcut-ref="allMethod"></aop:after-returning>
<aop:around method="around" pointcut-ref="allMethod"></aop:around>
<aop:after method="after" pointcut-ref="allMethod" />
</aop:aspect>
</aop:config>
</beans>

5.编写测试类

    public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("aop.xml"); IHelloWorld hw1 = (IHelloWorld)ac.getBean("helloWorldImpl1");
IHelloWorld hw2 = (IHelloWorld)ac.getBean("helloWorldImpl2");
hw1.printHelloWorld();
System.out.println();
hw1.doPrint(); System.out.println();
hw2.printHelloWorld();
System.out.println();
hw2.doPrint();
}

使用spring aop开发 就不需要我们手写动态代理代码了,还封装了cglib代理。可以对任何类进行代理增强。

spring的aop注解配置

<?xml version="1.0" encoding="UTF-8"?>
<!--导入aop命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!--配置目标对象 -->
<bean id="helloWorldImpl1" class="com.david.bean.HelloWorldImpl1" />
<bean id="helloWorldImpl2" class="com.david.bean.HelloWorldImpl2" />
<!--配置通知对象 -->
<bean id="myAdvice" class="com.david.bean.MyAdvice" /> <!--开启使用注解织入目标对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

通知类 使用注解设置

@Aspect //表示该类是一个通知类
public class MyAdvice {
@Before("execution(* com.david.bean.IHelloWorld.*(..))") //是一个前置通知并指定切入点
public void before() {
System.out.println("前置通知");
}
@After("execution(* com.david.bean.IHelloWorld.*(..))")
public void after() {
System.out.println("后置通知,无论异常与否都会调用");
} @AfterReturning("execution(* com.david.bean.IHelloWorld.*(..))")
public void afterRuning() {
System.out.println("后置通知,出现异常不会调用");
} @Around("execution(* com.david.bean.IHelloWorld.*(..))")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前通知");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("环绕后通知");
} }

再次运行 效果一样的。 抽取切入点

package com.david.bean;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*; @Aspect //表示该类是一个通知类
public class MyAdvice {
//定义一个切入点规则
@Pointcut("execution(* com.david.bean.IHelloWorld.*(..))")
public void pc(){ } @Before("MyAdvice.pc()")
public void before() {
System.out.println("前置通知");
}
@After("MyAdvice.pc()")
public void after() {
System.out.println("后置通知,无论异常与否都会调用");
} @AfterReturning("MyAdvice.pc()")
public void afterRuning() {
System.out.println("后置通知,出现异常不会调用");
} @Around("MyAdvice.pc()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前通知");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("环绕后通知");
} }

spring注解、aop(二)的更多相关文章

  1. Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils

    Spring 注解(二)注解工具类 AnnotationUtils 和 AnnotatedElementUtils Spring 系列目录(https://www.cnblogs.com/binary ...

  2. Spring 注解(二)注解工具类

    本文转载自Spring 注解(二)注解工具类 导语 首先回顾一下 AnnotationUtils 和 AnnotatedElementUtils 这两个注解工具类的用法: @Test @GetMapp ...

  3. Spring之AOP二

    在Spring之AOP一中使用动态代理将日志打印功能注入到目标对象中,其实这就是AOP实现的原理,不过上面只是Java的实现方式.AOP不管什么语言它的几个主要概念还是有必要了解一下的. 一.AOP概 ...

  4. Spring学习(六)—— Spring注解(二)

    核心原理 1.       用户发送请求给服务器.url:user.do 2.       服务器收到请求.发现Dispatchservlet可以处理.于是调用DispatchServlet. 3.  ...

  5. Spring注解 - AOP 面向切面编程

    基本概念: AOP:Aspect Oriented Programming,即面向切面编程 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式 前置通知(@Before):在目标 ...

  6. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  7. Spring注解AOP及单元测试junit(6)

    2019-03-10/20:19:56 演示:将xml配置方式改为注解方式 静态以及动态代理推荐博客:https://blog.csdn.net/javazejian/article/details/ ...

  8. spring 注解AOP

     aspectAnnotation的切面信息,加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了. 解析annotationSe ...

  9. 重新学习Spring注解——AOP

    面向切面编程——思想:在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处运用,而无须修改受影响的类. 切面:横切关注点可以被模块化为特殊的类. 优点: 1.每个关注点都集中在 ...

  10. spring注解 aop

    @Resource(name="as")  为空按类型装配 @autowired 按类型 @quafiler (name="xx") 按名称 spring继承关 ...

随机推荐

  1. 什么是ACID

    ACID是衡量事务的四个特性: 原子性(Atomicity,或称不可分割性) 一致性(Consistency) 隔离性(Isolation) 持久性(Durability) 原子性:原子性是指一个事务 ...

  2. How To: set udev rule for setting the disk permission on ASM disks when using multipath on Linux 6.x

    在RHEL6.4上安装11gR2的RAC时,使用了MULTIPATH来聚合绑定多路径的磁盘,并且修改磁盘的权限,赋予grid:asmadmin用户和组. 此时,在安装时可以发现磁盘,日志如下 INFO ...

  3. 新浪微博API生成短链接

    通过新浪微博API,生成短链接,支持一次性转多个长链接 什么是短链接 短链接,通俗来说,就是将长的URL网址,通过程序计算等方式,转换为简短的网址字符串. 短链接服务 国内各大微博都推出了自己的短链接 ...

  4. BZOJ 2501 [usaco2010 Oct]Soda Machine

    [题意概述] 给出一个[0,1,000,000,000]的整数数轴,刚开始每个位置都为0,有n个区间加操作,最后询问数轴上最大的数是多少. [题解] 我写的是离散化后线段树维护区间最值. 其实貌似不用 ...

  5. jquery源码分析(三)——工具函数

    jQuery.extend({ expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "&quo ...

  6. Pillow 模块~Python图像处理

    什么是验证码? 验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自 ...

  7. GlobalSign 增强型(EV) SSL 证书

    GlobalSign 增强型(EV) SSL 证书,属于最高验证级别的EV SSL,验证域名所有权,进行严格的企业真实身份验证,证书标识企业组织机构名称,强化信任度,浏览器地址栏变绿色.提供40位/5 ...

  8. 【Codeforces Global Round 1 A】Parity

    [链接] 我是链接,点我呀:) [题意] 给你一个k位数b进制的进制转换. 让你求出来转成10进制之后这个数字是奇数还是偶数 [题解] 模拟一下转换的过程,加乘的时候都记得对2取余就好 [代码] im ...

  9. 【Codeforces 158B】Taxi

    [链接] 我是链接,点我呀:) [题意] 每辆车可以载重4个人. 一共有n个组,每个组分别有s[i]个人. 要求每个组的人都在同一辆车里面. 问最少需要多少辆车 [题解] 将每个组的人数从小到大排序. ...

  10. CSVHelper在Asp.Net MVC中的使用

    1,从数据库读取数据,然后导出CSV文件 [HttpPost] public FileResult ExportCSV() { var apps =....//linq以及EF从数据库查询数据 Mem ...