自动创建代理-BeanNameAutoProxyCreator

/ Spring / 没有评论 / 355浏览

在其它的文章中我们基本都是采用ProxyFactoryBean类来创建代理类的,但在使用此类时,我们通常要设置很多属性不方便我们使用。在spring中我们还可以使用BeanNameAutoProxyCreator类以更加优雅的方式为我们创建代理类。下面我们看一下该类的使用:

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 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 UserServiceBeforeAdvice implements MethodBeforeAdvice{

@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(String.format("spring增强: %s", method.getName()));
TransactionManager.beginTransaction();
}
}
<bean id="userService" class="com.jilinwula.spring.aop.UserService"/>
<bean id="userServiceImpl" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean id="userServiceBeforeAdvice" class="com.jilinwula.spring.aop.UserServiceBeforeAdvice"/>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
p:beanNames="*Impl"
p:interceptorNames="userServiceBeforeAdvice"
p:optimize="true"/>
@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");
}
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
spring增强: register
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula

BeanNameAutoProxyCreator类中有一个beanNames属性,它可以通过*通配符来匹配对象名称,来自动添加增强。在上述代码中因为我们匹配的是Impl所以只会在UserServiceImpl类中添加增强,如果我们希望两个类都添加增强可以采用以下的方法匹配。

<bean id="userService" class="com.jilinwula.spring.aop.UserService"/>
<bean id="userServiceImpl" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean id="userServiceBeforeAdvice" class="com.jilinwula.spring.aop.UserServiceBeforeAdvice"/>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
p:beanNames="user*"
p:interceptorNames="userServiceBeforeAdvice"
p:optimize="true"/>
spring增强: register
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
spring增强: register
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula