我在service定义一个目标类,用于输出"您登录了"
我又定义了一个切面类,里面通知为输出"登陆前检查!",通过切入点@before
现在我在service层的目标类中织入这个切面类的通知,在controller层里面调用service层的输入,理想状态下是输出
"登陆前检查!"
"您登陆了"
但是现在它执行了两次,这是为什么呀?
切面类
package com.experience.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAspect {
@Pointcut("execution(void com.experience.service.LoginService.login())")
private void method(){}
@Before("method() ")
public void show(){
System.out.println("登录前检查!");
}
}
controller层
package com.experience.controller;
import com.experience.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginTest {
@Autowired
LoginService loginService;
@RequestMapping(value = "/denglu")
public void login()
{
loginService.login();
}
}
service代码(目标类)
package com.experience.service;
import org.springframework.stereotype.Service;
@Service
public class LoginService {
public void login(){
System.out.println("您登录了!");
}
}
输出结果
配置文件'
<?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: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.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解扫描,扫描包-->
<context:component-scan base-package="com.experience.service"/>
<context:component-scan base-package="com.experience.aspect"/>
<aop:aspectj-autoproxy/>
</beans>