Java实体类去除空格
时间: 2023-09-21 21:11:33 浏览: 136
可以使用注解 @Trim 将实体类中字符串类型的属性去除空格。注解的实现可以参考 StringUtils.trim() 方法,对字符串进行去除空格操作。具体实现可以参考以下代码:
```java
public class User {
private Long id;
@Trim
private String name;
@Trim
private String address;
// 省略其它属性和 getter、setter 方法
}
```
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Trim {
}
```
```java
public class TrimInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
Field[] fields = target.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Trim.class) && field.getType() == String.class) {
field.setAccessible(true);
Object value = field.get(target);
if (value != null) {
field.set(target, StringUtils.trim((String) value));
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// do nothing
}
}
```
在 Spring Boot 项目中,配置如下:
```java
@Configuration
public class MyBatisConfig {
@Bean
public Interceptor trimInterceptor() {
return new TrimInterceptor();
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, Interceptor trimInterceptor) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPlugins(new Interceptor[]{trimInterceptor});
return bean;
}
}
```
这样就可以在 Mybatis 执行 SQL 之前对实体类进行去除空格操作了。
阅读全文