初学spring aop 注解遇到的问题



      初学spring,对spring注解这块了解不是很多,现在注解替代了xml配置文件,原来的bean id 去哪里了呢?

//@Service//默认类名
@Service("rmb")//这就是bean的id。

直接注解的话,会默认类的名字作为bean的id。也可以在@Service(“RMB”)这是自定义bean id。这样就很直观了。


spring配置文件的没有想象那么简单,我在网上找了很多关于spring aop 的例子。基本都没有配置文件的头。这个头会引发很多错误。

下面我改了一下我在网上复制下来的例子。并把自己遇到问题写下来。这是一个基本的spring aop 例子

首先配置文件

<?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:aop="http://www.springframework.org/schema/aop"
    		xmlns:tool="http://www.springframework.org/schema/tool" 
    		  xmlns:context="http://www.springframework.org/schema/context"         
            xsi:schemaLocation="
     http://www.springframework.org/schema/beans             
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd          
     http://www.springframework.org/schema/aop         
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 
    <!-- 启用AspectJ对Annotation的支持 -->       
		<!-- 激活annotation功能 -->
		<context:annotation-config />
		<!-- 激活aop功能 -->
		<aop:aspectj-autoproxy/>
			
			
			<!--<bean id="myInterceptor" class="com.tgb.aop.LogAspect"/> 
			-->
			<!-- 让spring 扫包下面对类,让注解生效 -->
			 <context:component-scan base-package="com.tgb.aop"
    scoped-proxy="targetClass">
</context:component-scan>

</beans>
这文件你可以自己命名,

下面是类

例子中是简单模拟使用钱,的切面例子

package com.tgb.aop;
public interface IPayService {
    String pay(long userId, long money);
}
这是接口,

创建主体

package com.tgb.aop;


import org.springframework.stereotype.Service;

//@Service//默认类名
@Service("rmb")//这就是bean的id。
public class RMBPayService implements IPayService {
    //private static final Logger LOGGER = LoggerFactory.getLogger(RMBPayService.class);
 
    @Override
    public String pay(long userId, long money) {
        System.out.println("用户:" + userId + "使用人民币支付金额:" + money);
        return "ok";
    }
}

创建切面

package com.tgb.aop;
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;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main.Logger;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {
 
    //private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);
 
	int i=0;
    @Pointcut("execution (* com.tgb.aop.RMBPayService.pay(..))")
    public void publicPointcut(){
    	System.out.println("这里是切点。该方法只是一个标示,供@Pointcut注解依附。"+i++);
    }
 
    @Before("publicPointcut()")//里面的值是切点的定义方法。
    public void before() {
        System.out.println("支付前打印一点字.........");
    }
    @Before("publicPointcut()")//里面的值是切点的定义方法。
    public void before2() {
        System.out.println("支付前打印一点字.33223232........");
    }
    @After("publicPointcut()")
    public void afterAdvice() {
        System.out.println("后置通知,支付完成了呵呵............");
    }
 
    
    
    // 注意,此处returning后的值必须与方法参数名的值一致
    @AfterReturning(value = "execution(public String com.tgb.aop.*.pay(..))", returning = "retVal")
    public void afterReturning(String retVal) {
        System.out.println("支付结果如何,检查检查:后置" + retVal);
    }
 
    @AfterThrowing(pointcut = "publicPointcut()", throwing = "ex")
    public void afterThrowing(Exception ex) {
        System.out.println(ex.getMessage());
    }
 
    // 此方法必须有返回值,否则会使得被代理的方法的返回值变为null,在此方法中可以修改返回值
    @Around("publicPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("支付方法中,环绕    先来一下........");
        Object result = joinPoint.proceed();
        System.out.println("支付方法结束了,走你.........");
        //改变运行结果。
        return result + "add";
    }
}

测试类

package com.tgb.aop;


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

public class Test {
	 private static ApplicationContext ctx;
	public static void main(String[] args) throws Exception{
		//加载配置文件。
		ctx = new ClassPathXmlApplicationContext("test.xml");
		//在注解时,名字会是默认的类名。
		IPayService service = (IPayService)ctx.getBean("rmb");
        System.out.println(service.pay(2000, 20000));
//		
//     	ApplicationContext act = new ClassPathXmlApplicationContext("test.xml");
//     	CommonEmployee e = (CommonEmployee)act.getBean("employee");
//        e.signIn();
		
	}
}


运行结果


log4j:WARN No appenders could be found for logger (org.springframework.core.io.support.PathMatchingResourcePatternResolver).
log4j:WARN Please initialize the log4j system properly.
支付方法中,环绕    先来一下........
支付前打印一点字.........
支付前打印一点字.33223232........
用户:2000使用人民币支付金额:20000
支付方法结束了,走你.........
后置通知,支付完成了呵呵............
支付结果如何,检查检查:后置okadd
okadd




整个项目在我的资源那里可以下载































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值