静态普通方法名匹配切面

/ Spring / 没有评论 / 311浏览

我们在使用增强时知道,横切逻辑会添加到目标类的所有方法中,无论是方法前还是方法后。而有时,我们只想将增强添加到我们需要添加的方法中,例如添加事物管理的增强。这时我们就要使用切点来完成这种需求了。在spring中可以通过Pointcut接口描述切点。Pointcut接口由两部分组成,它们分别是ClassFilter和MethodMatcher构成。顾名思义,看名称我们知道前者是定位到某些特定的类上的,而后者是定位到某些特定的方法上的。正是因为如此,切点才可以定位到某些类的某些具体方法。

在spring中通过Advisor接口来表示切面,切面也就是同时包括横切代码和连接点的信息。切面可分为3种类型,它们分别是:

public class UserServiceImpl implements IUserService {

public void login(String username, String password) {
System.out.println(String.format("用户登陆: username: %s password: %s", username, password));
}

public void register(String username, String nickName, String password) {
System.out.println(String.format("用户注册: username: %s nickName: %s password: %s", username, nickName, password));
}

}
public class UserService{

public void login(String username, String password) {
System.out.println(String.format("用户登陆: username: %s password: %s", username, password));
}

public void register(String username, String nickName, String password) {
System.out.println(String.format("用户注册: username: %s nickName: %s password: %s", username, nickName, password));
}

}
public class UserServiceAdvisor extends StaticMethodMatcherPointcutAdvisor {

@Override
public boolean matches(Method method, Class<?> targetClass) {
return "register".equals(method.getName());
}

@Override
public ClassFilter getClassFilter() {
return new ClassFilter() {
@Override
public boolean matches(Class<?> clazz) {
return UserService.class.isAssignableFrom(clazz);
}
};
}
}
<bean id="userServiceImplTarget" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean id="userServiceTarget" class="com.jilinwula.spring.aop.UserService"/>
<bean id="userServiceBeforeAdvice" class="com.jilinwula.spring.aop.UserServiceBeforeAdvice"/>
<bean id="userServiceAdvisor" class="com.jilinwula.spring.aop.UserServiceAdvisor" p:advice-ref="userServiceBeforeAdvice"/>
<bean id="parent" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean"
p:interceptorNames="userServiceAdvisor"
p:proxyTargetClass="true"
/>
<bean id="userServiceImpl" parent="parent" p:target-ref="userServiceImplTarget"/>
<bean id="userService" parent="parent" p:target-ref="userServiceTarget"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UserService userService = applicationContext.getBean("userService", UserService.class);
UserServiceImpl userServiceImpl = applicationContext.getBean("userServiceImpl", UserServiceImpl.class);
userService.register("admin","吉林乌拉","jilinwula");
userServiceImpl.register("admin","吉林乌拉","jilinwula");
}
spring增强
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula