Spring boot——@DeclareParents例子

通过spring aop的@DeclareParents为某个类(及其所有子类)动态代理新增实现接口
本节代码 https://download.csdn.net/download/wangwjtt/10908155

修改上节代码(https://blog.csdn.net/wangwjtt/article/details/86210943) ,新增@DeclareParents注解
目录结构如下
在这里插入图片描述
Controller

	@RequestMapping("/test")
	@ResponseBody
	public User validateAndPrint(Integer id) {
		System.out.println("User");
		User user = new User();
		user.setId(id);
		user.setUsername("wang.li");
		user.setNote("AAA");
		UserValidator userValidator = (UserValidator) userService;
		if(userValidator.myYalidate(user)) {
			userService.printUser(user);
		}
		return user;
	}

UserService

import com.springboot.chapter4.pojo.User;

public interface UserService {
	public void printUser(User user);
}

UserServiceimpl

/**
 * @Service 是标记实现类上的。
  *   因为@Service是把spring容器中的bean进行实例化,也就是等同于new操作,
  *   只有实现类是可以进行new实例化的,而接口则不能,所以是加在实现类上的。不信你标注到接口上,会报BeanCreationException的。
 * @author XXX
 *
 */@Service
public class UserServiceimpl implements UserService{
	@Override
	public void printUser(User user) {
		// TODO Auto-generated method stub
		if(user == null) {
			throw new RuntimeException("检查用户参数是否为空. .. ...");
		}
		System.out.println("id = "+user.getId());
		System.out.println("username = "+user.getUsername());
		System.out.println("note = "+user.getNote());
	}
}

UserValidator //为了增强UserService接口功能(本接口功能 检测User是否为空)

import com.springboot.chapter4.pojo.User;
/**
 * 为了增强UserService接口功能(本接口功能 检测User是否为空)
 * @author jiantao.wang
 *
 */
public interface UserValidator {
	public boolean myYalidate(User user);
}

UserValidatorImpl

public class UserValidatorImpl implements UserValidator{
	@Override
	public boolean myYalidate(User user) {
		// TODO Auto-generated method stub
		System.out.println("引入新的接口:"+UserValidator.class.getSimpleName());
		return user != null;
	}
}

MyAspect

  @DeclareParents
	  value:要增强功能的目标对象(要增强的对象)
	  defaultImpl:引入增强的类
	  "+" UserServiceimpl的所有子类
	/**
	 * value:要增强功能的目标对象(要增强的对象)
	 * defaultImpl:引入增强的类
	 * "+" UserServiceimpl的所有子类
	 */
	@DeclareParents(value = "com.springboot.chapter4.aspect.service.impl.UserServiceimpl+",defaultImpl=UserValidatorImpl.class)
	public UserValidator userValidator;

Controller

		UserValidator userValidator = (UserValidator) userService;
		if(userValidator.myYalidate(user)) {
			userService.printUser(user);
		}	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值