欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dubbo源码 学习笔记(五)

程序员文章站 2022-06-01 17:45:20
...

dubbo  接口 Validator


dubbo源码 学习笔记(五)

字dubbo的过滤器中 自带了一个javax.validation的验证器


服务端配置

service.setValidation("jvalidation");

xml的配置方式

<!-- 声明需要暴露的服务接口 -->
    <dubbo:service interface="com.alibaba.dubbo.demo.DemoService" ref="demoService" va="jvalidation"/>

引入jar包

		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.Final</version>
		</dependency>

接口定义

public interface HelloService {
	
	int say(User hello);
}
实体类定义
public class User implements Serializable {

	private static final long serialVersionUID = 1609415403100275799L;

	@NotNull(message ="不能为空")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	private String name;
}


消费端测试代码

			HelloService helloService = reference.get();
			
			User user = new User();
//			user.setName("w");
			System.out.println(helloService.say(user));
		

运行 name 为空时 会报异常

com.alibaba.dubbo.rpc.RpcException: Failed to validate service: com.wy.demo.dubbo.service.HelloService, method: say, cause: [ConstraintViolationImpl{interpolatedMessage='不能为空', propertyPath=name, rootBeanClass=class com.wy.demo.dubbo.module.User, messageTemplate='不能为空'}]