Spring中使用注解实现Bean的装配和AOP

配置applicationContext.xml 

//开启包扫描

<context:component-scan base-package="com.qst"/>

//开启注解
   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

一:基于注解的装配

1)类的修饰

@Component:适用于任何类

@Repository:适用于DAO

@Service:适用于service

@Controller:适用于controller

2)类之间的依赖

@Autowired:按类型注入,若想附加按名称查找:

                         @Autowired@Qualifier("类名称");

@Resource:先按名称注入,名称找不到时再按类型

二:SpringAOP基于注解配置

新增所需jar包

Spring-aop ,spring-aspects ,spring-expression,aspectjweaver , aopalliance

//切面类
package com.qst;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("annotationTest")
@Aspect
public class AnnotationTest {
     //定义切点
     @Pointcut("execution(* *.saying(..))")
    public void sayings(){}
    /**    * 前置通知(注解中的sayings()方法,其实就是上面定义pointcut切点注解所修饰的方法名,那只是个代理对象,不需要写具体方法,
      * 相当于xml声明切面的id名,如下,相当于id="embark",用于供其他通知类型引用)
     * <aop:config>
        <aop:aspect ref="mistrel">
           <!-- 定义切点 -->
            <aop:pointcut expression="execution(* *.saying(..))" id="embark"/>
            <!-- 声明前置通知 (在切点方法被执行前调用) -->
            <aop:before method="beforSay" pointcut-ref="embark"/>             <!-- 声明后置通知 (在切点方法被执行后调用) -->
             <aop:after method="afterSay" pointcut-ref="embark"/>         </aop:aspect>
        </aop:config>
     */
    @Before("sayings()")
    public void sayHello(){
         System.out.println("注解类型前置通知");
     }
    //后置通知
    @After("sayings()")
    public void sayGoodbey(){
         System.out.println("注解类型后置通知");
     }
    //环绕通知。注意要有ProceedingJoinPoint参数传入。
     @Around("sayings()")
     public void sayAround(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("注解类型环绕通知..环绕前");
        pjp.proceed();//执行方法
        System.out.println("注解类型环绕通知..环绕后");
    }
 }



//被增强的类。他自己并不知道被增强
package com.qst.dao;

import org.springframework.stereotype.Component;
@Component("knight")
public class Knight {
	    public void saying(){
	         System.out.println("我是骑士..(切点方法)");
	     }
}

//测试类

package com.qst.SpringDemo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qst.dao.Knight;

public class Test {
	@org.junit.Test
	public void test() {
		        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		        Knight br = (Knight) ac.getBean("knight");
		        br.saying();
		    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42648580/article/details/82621227