Spring学习笔记二 注解及AOP

注解:  使用注解的目的是为了代替配置,在使用注解时,省略键时,则是为value赋值。 扫描某个包下的所有类中的注解。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context 
                                           http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop 
                                           http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
<!-- 指定扫描cn.itcast.bean包下的所有类中的注解. 注意:扫描包时.会扫描指定包下的所有子孙包-->
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>
</beans>

1、将对象注册到Spring容器中。可以使用下面四种方式。

@Component("user")

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

public class User {}

 2、修改对象的作用范围:

//指定对象的作用范围,默认単例
@Scope(scopeName="singleton")
public class User {}

3、值类型注入:

方式一:直接把@Value加到字段上,通过反射为Field赋值,破坏了封装性。

复制代码
public class User {
    @Value("tom")
    private String name;
    @Value("18")
    private Integer age;
}
复制代码

方式二:把@Value加到setName方法上,通过set方法赋值,推荐使用。

    @Value("tom")    
    public void setName(String name) {
        this.name = name;
    }

4、引用类型注入

方式一:使用@Autowired(自动装配),此种方式如果匹配多个类型一致的对象,将无法选择具体注入哪一个对象。

@Component("car")
public class Car {}

@Component("user")
public class User {
    @Autowired //自动装配
    private Car car;
}

方式二 :使用@Qualifier注解告诉spring容器自动装配哪个名称的对象,必须配套使用。

@Component("car")
public class Car {}
@Component("user") public class User { @Autowired //自动装配 @Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象 private Car car; }

方式三:使用@Resource,手动指定注入哪个名称的对象

public class User {
    @Resource(name="car")//手动注入,指定注入哪个名称的对象
    private Car car;
}

5、初始化|销毁方法

public class User {
    @PostConstruct //在对象被创建后调用.init-method
    public void init(){
        System.out.println("我是初始化方法!");
    }
    @PreDestroy //在销毁之前调用.destory-method
    public void destory(){
        System.out.println("我是销毁方法!");
    }
}

Spring与Junit整合demo测试:

1、导包 spring-test-4.2.4.RELEASE.jar

2、在类上配置注解:

//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")

3、测试:

复制代码
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    //将名为user的对象注入到u变量中
    @Resource(name="user")
    private User u;
    
    @Test
    public void fun1(){
        System.out.println(u);
    }
    
    @Test
    public void fun2(){
        System.out.println(u);
    }
    
    @Test
    public void fun3(){
        System.out.println(u);
    }
}

Spring AOP:

 1、导包:

  1. spring-aspects-4.2.4.RELEASE.jar
  2. spring-aop-4.2.4.RELEASE.jar

spring需要第三方aop包:

  1. com.springsource.org.aopalliance-1.0.0.jar
  2. com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

2、准备目标对象

复制代码
package cn.itcast.service;

public class UserServiceImpl implements UserService {
    @Override
    public void save() {
        System.out.println("保存用户!");
        //int i = 1/0;
    }
    @Override
    public void delete() {
        System.out.println("删除用户!");
    }
    @Override
    public void update() {
        System.out.println("更新用户!");
    }
    @Override
    public void find() {
        System.out.println("查找用户!");
    }
}
复制代码

3、准备通知:

package cn.itcast.d_springaop;
import org.aspectj.lang.ProceedingJoinPoint;

//通知类
public class MyAdvice {
    
    //前置通知    
//        |-目标方法运行之前调用
    //后置通知(如果出现异常不会调用)
//        |-在目标方法运行之后调用
    //环绕通知
//        |-在目标方法之前和之后都调用
    //异常拦截通知
//        |-如果出现异常,就会调用
    //后置通知(无论是否出现 异常都会调用)
//        |-在目标方法运行之后调用
//----------------------------------------------------------------
    //前置通知
    public void before(){
        System.out.println("这是前置通知!!");
    }
    //后置通知
    public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }
    //环绕通知
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }
    //异常通知
    public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }
    //后置通知
    public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}
复制代码

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

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

<!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
    <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
    <bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" ></bean>
<!-- 3.配置将通知织入目标对象 -->
    <aop:config>
        <!-- 配置切入点 
            public void cn.itcast.service.UserServiceImpl.save() 这样配置太啰嗦
            void cn.itcast.service.UserServiceImpl.save() public可以省
            * cn.itcast.service.UserServiceImpl.save() 对返回值不做任何要求
            * cn.itcast.service.UserServiceImpl.*() 所有空参方法
            
            * cn.itcast.service.*ServiceImpl.*(..) 找service包下的所有ServiceImpl结尾的方法
            * cn.itcast.service..*ServiceImpl.*(..) 找Service包下(及其子孙包)的所有的ServiceImpl结尾的方法
        -->
        <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/>
        <aop:aspect ref="myAdvice" >
            <!-- 指定名为before方法作为前置通知 -->
            <aop:before method="before" pointcut-ref="pc" />
            <!-- 后置 -->
            <aop:after-returning method="afterReturning" pointcut-ref="pc" />
            <!-- 环绕通知 -->
            <aop:around method="around" pointcut-ref="pc" />
            <!-- 异常拦截通知 -->
            <aop:after-throwing method="afterException" pointcut-ref="pc"/>
            <!-- 后置 -->
            <aop:after method="after" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>
</beans>
复制代码

5、测试代码

复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {

    @Autowired
    private UserService u;

    @Test
    public void fun1() {
      u.save();
    }

}
复制代码

另一种方式:使用注解演示AOP:

 配置文件:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

<!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
    <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
    <bean name="myAdvice" class="cn.itcast.e_annotationaop.MyAdvice" ></bean>
<!-- 3.开启使用注解完成织入 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
复制代码

通知类:

复制代码
package cn.itcast.e_annotationaop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

//通知类
@Aspect
//表示该类是一个通知类
public class MyAdvice {
    @Pointcut("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void pc(){}//抽取相同的execution,方便管理。
    //前置通知
    //指定该方法是前置通知,并制定切入点
    @Before("MyAdvice.pc()")
    public void before(){
        System.out.println("这是前置通知!!");
    }
    //后置通知
    @AfterReturning("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }
    //环绕通知
    @Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }
    //异常通知
    @AfterThrowing("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }
    //后置通知
    @After("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}
原文地址:https://www.cnblogs.com/lgg20/p/11187462.html