springboot实现字段加密注解

1、创建一个注解类

@Documented 
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) 
public @interface DataEncrypt { 

}

2、项目启动时加载自定义ObjectMapper

@Configuration
public class ObjectMapperConfig {
	
	@Bean
	@Primary
	ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper mapper = builder.createXmlMapper(false).build();
		AnnotationIntrospector sis = mapper.getSerializationConfig().getAnnotationIntrospector();
		AnnotationIntrospector is1 = AnnotationIntrospector.pair(sis, new DataAnnotationIntrospector());
		mapper.setAnnotationIntrospector(is1);
		return mapper;
	}
}

3、自定义绑定序列化类和相关字段的关联关系

public class DataAnnotationIntrospector extends NopAnnotationIntrospector {
	@Override
	public Object findSerializer(Annotated am){
	
		DataEncrypt annotation = am.getAnnotation(DataEncrypt.class);
		if (annotation != null) {
			return DataSerializer.class
		}
		return null;
	}
}

4、 自定义标准序列化类对具体的字段进行加密处理

public class DataSerializer extends StdSerializer {
	public DataSerializer() {
		super(Object.class);
	}

	@Override
	public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
		if (value == null) return;
		try {
                        // 根据自己需要的算法加密字段内容
			String encryptStr = AESUtil.encrypt(value.toString());
			jsonGenerator.writeString(encryptStr );
		} catch (Exception e) {

		}
	}
	
}
 
  

5、注解加在字段上进行使用

@DataEncrypt
private String username;

你可能感兴趣的:(java实战,spring,boot,java,spring)