上一篇參考文章
/**
* @description:
* @Author C_Y_J
* @create 2021-03-03 09:57
**/
public interface TargetInterface {
void save();
}
/**
* @description:
* @Author C_Y_J
* @create 2021-03-03 09:57
**/
@Component("targetInterfaceImpl")
public class TargetInterfaceImpl implements TargetInterface {
@Override
public void save() {
System.out.println("目标接口的實作 run ...");
}
}
/**
* @description:
* @Author C_Y_J
* @create 2021-03-03 09:56
**/
@Component("aspect")
@org.aspectj.lang.annotation.Aspect
public class Aspect {
@Before("execution(* com.cyj.springaop1.anno.*.*(..))")
public void before() {
System.out.println("前置增強");
}
public void afterReturning() {
System.out.println("後置增強");
}
}
applicationContext-anno.xml:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--開啟注解掃描-->
<context:component-scan base-package="com.cyj.springaop1.anno"></context:component-scan>
<!--aop自動代理-->
<aop:aspectj-autoproxy/>
</beans>
測試:
/**
* @description:
* @Author C_Y_J
* @create 2021-03-02 11:42
**/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoTest {
@Autowired
private TargetInterface targetInterface;
@Test
public void test1() {
targetInterface.save();
}
}