Spring自定义属性解析,PropertyEditor的使用

PropertyEditor的使用

PropertyEditor是spring提供的一种对属性自定义解析的一种方式,如:用户传入时间戳,直接将其转换为LocalDate

spring中的使用

1. 定义自定义PropertyEditor

这里使用的PropertyEditorSupport是spring提供的PropertyEditor的实现,直接继承使用,主要重写setAsText方法对属性的转换

package com.armin.self_editor;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;

public class LocalDatePropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Long timeMillis = null;
        try {
            timeMillis = Long.valueOf(text);
        } catch (NumberFormatException e) {
          	//todo 转换异常的处理
        }
     		LocalDate localDate = Instant.ofEpochMilli(timeMillis).atZone(ZoneOffset.ofHours(8)).toLocalDate();
        this.setValue(localDate);
    }
}

2. 将其注册到自定义的编辑器中

这里需要实现PropertyEditorRegistrar并重写registerCustomEditors方法

package com.armin.self_editor;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import java.time.LocalDate;

public class LocalDatePropertyEditorRegistrar implements PropertyEditorRegistrar {

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor());
    }
}

3. 编写转换的demo

package com.armin.self_editor;

import java.time.LocalDate;

@Data
public class DateCustomer {
    private LocalDate date;
}

4. 配置xml文件

注入解析的bean并将自定义属性编辑器注册到CustomEditorConfigurer

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="customer" class="com.armin.self_editor.DateCustomer">
          <property name="date" value="1694534400000"/>
      </bean>
  		<!--注册CustomEditorConfigurer Bean finishBeanFactoryInitialization()中会调用registerCustomEditors-->
      <!--一共实例化了3个对象均在此处定义了:实例化顺序CustomEditorConfigurer,AddressPropertyEditorRegistrar,Customer-->
  		<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    			<property name="propertyEditorRegistrars">
  						<list>-->
  		            <bean class="com.armin.self_editor.LocalDatePropertyEditorRegistrar"/>
  			      </list>
         	</property>
  		</bean>

      <!--方式二-->
      <!--上面的方式最终也会调用LocalDatePropertyEditorRegistrar的registerCustomEditors设置LocalDatePropertyEditor到属性customEditors中-->
      <!--与此处直接设置到customEditors属性中其效果一致-->
<!--      <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">-->
<!--        	<property name="customEditors">-->
<!--              <map>-->
<!--                  <entry key="java.time.LocalDate">-->
<!--                      <value>com.armin.self_editor.LocalDatePropertyEditor</value>-->
<!--                  </entry>-->
<!--              </map>-->
<!--        	</property>-->
<!--    	</bean>-->
</beans>

4. 测试类

package com.armin.self_editor;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SelfEditorTest {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("armin-self-editor.xml");
        DateCustomer customer = ac.getBean(DateCustomer.class);
        System.out.println(customer);
    }

}

springboot中的使用

如果想要在Controller层对web传入的参数进行自定义转换处理需要实现WebBindingInitializer接口,在initBinder方法中使用传入的WebDataBinder参数调用registerCustomEditor传入我们需要转换的类型与自定义转换处理的PropertyEditor对象

package com.armin.self_editor;

import com.armin.self_editor.LocalDatePropertyEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;

import java.time.LocalDate;

public class MyWebBindingInitializer implements WebBindingInitializer {
  	@Override
  	public void initBinder(WebDataBinder webDataBinder) {
      	webDataBinder.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor());
    }
}

然后将该对象设置到RequestMappingHandlerAdapter中的webBindingInitializer属性中

package com.armin.self_editor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.Resource;

@Configuration
public class WebConfiguration {
  	@Resource
  	public void setWebBindingInitializer (RequestMappingHanlderAdapter adapter) {
      	adapter.setWebBindingInitializer(new MyWebBindingInitializer());
    }
}

至此已完成了Controller层传参的全局处理(时间戳转换为LocalDate的处理)

同时如果需要对单个Controller中使用该转换可以在需要转换的Controller加入如下代码

@InitBinder
public void initBinder(WebDataBinder binder) {
  	binder.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor());
}

WebDataBinder实际上就是实现了PropertyEditorRegistrySpringBoot中的一种封装方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值