Spring注入Date类型的三种方法总结

Spring注入Date类型的三种方法总结

测试Bean:

public class DateBean {
  private Date birthday; 

  public Date getBirthday() {
    return birthday;
  } 

  public void setBirthday(Date birthday) {
    this.birthday = birthday;
  }
}

方式1:利用SimpleDateFormat的构造方法注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p" 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="dateFormat" class="java.text.SimpleDateFormat">
  <constructor-arg value="yyyy-MM-dd" />
  </bean> 

  <bean id="datebean" class="com.springDemo1.Date类型注入.DateBean">
    <property name="birthday">
      <bean factory-bean="dateFormat" factory-method="parse">
        <constructor-arg value="2015-12-31" />
      </bean>
    </property>
  </bean>
</beans>

方式2:纯配置,先自定义CustomDateEditor,再转换类型

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p" 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="dateEditor"
    class="org.springframework.beans.propertyeditors.CustomDateEditor">
    <constructor-arg>
      <bean class="java.text.SimpleDateFormat">
        <constructor-arg value="yyyy-MM-dd"></constructor-arg>
      </bean>
    </constructor-arg>
    <constructor-arg value="true" />
  </bean>
  <!-- 使 Spring转换为java.util.Date -->
  <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
      <map>
        <entry key="java.util.Date">
          <ref bean="dateEditor" />
        </entry>
      </map>
    </property>
  </bean>
</beans>

方式3:先用一个类重写PropertyEditorSupport的setAsText方法,再在配置文件中,配置转换类型就可以了,跟上面方法类似

public class MyDatePropertyEditor extends PropertyEditorSupport {
  private String format; 

  public String getFormat() {
    return format;
  } 

  public void setFormat(String format) {
    this.format = format;
  } 

  // text为需要转换的值,当为bean注入的类型与编辑器转换的类型匹配时就会交给setAsText方法处理
  public void setAsText(String text) throws IllegalArgumentException {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
      this.setValue(sdf.parse(text));
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p" 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"> 

  <!--方式3:创建一个类 重写PropertyEditorSupport的setAsText方法 -->
  <!-- 自定义日期编辑器 -->
  <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors"> <!--需要编辑的属性类型,是一个map -->
      <map>
        <entry key="java.util.Date">
          <bean class="com.springDemo1.Date类型注入.MyDatePropertyEditor">
            <property name="format" value="yyyy-MM-dd" /> <!--注入需要转换的格式 -->
          </bean>
        </entry>
      </map>
    </property>
  </bean>
</beans>

测试:

public class DateTest {
  @Test
  public void testName() throws Exception { 

    ApplicationContext context = new ClassPathXmlApplicationContext(
        "applicationContext.xml"); 

    DateBean bean = (DateBean) context.getBean("datebean");
    System.out.println(bean.getBirthday());
  }
}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • 简单了解Spring中常用工具类

    文件资源操作 Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名.URL 地址以及资源内容的操作方法 访问文件资源 * 通过 FileSystemResource 以文件系统绝对路径的方式进行访问: * 通过 ClassPathResource 以类路径的方式进行

  • spring boot加载第三方jar包的配置文件的方法

    前言 今天收到一封邮件,大概内容如下:spring boot鼓励去配置化,那么怎么将第三方jar包中的xml去配置化了? 其实,这个问题,在前面的文章中也有提到,http://www.jb51.net/article/125700.htm 下面,我们就以Quartz定时任务为例,单独对这个问题来进行说明,如何实现去配置化. 如果不使用spring boot,我们配置一个简单的定时任务时,需要引入以下配置文件: <!-- 配置需要定时执行的任务类以及方法 --> <bean id=&quo

  • 详解SpringBoot 快速整合MyBatis(去XML化)

    序言: 此前,我们主要通过XML来书写SQL和填补对象映射关系.在SpringBoot中我们可以通过注解来快速编写SQL并实现数据访问.(仅需配置:mybatis.configuration.map-underscore-to-camel-case=true).为了方便大家,本案例提供较完整的层次逻辑SpringBoot+MyBatis+Annotation. 具体步骤 1. 引入依赖 在pom.xml 引入ORM框架(Mybaits-Starter)和数据库驱动(MySQL-Conn)的依赖.

  • Spring Java-based容器配置详解

    装Java-based的配置 使用 @Import 注解 跟在Spring XML文件中使用<import>元素添加模块化的配置类似,@Import注解允许你加载其他配置类中的@Bean定义: @Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public

  • 解决springMVC 跳转js css图片等静态资源无法加载的问题

    web.xml中 servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-va

  • SpringCloud实战小贴士之Zuul的路径匹配

    不论是使用传统路由的配置方式还是服务路由的配置方式,我们都需要为每个路由规则定义匹配表达式,也就是上面所说的 path 参数.在Zuul中,路由匹配的路径表达式采用了Ant风格定义. Ant风格的路径表达式使用起来非常简单,它一共有下面这三种通配符: 通配符 说明 ? 匹配任意的单个字符 * 匹配任意数量的字符 ** 匹配任意数量的字符,支持多级目录 我们可以通过下表的示例来进一步理解这三个通配符的含义并参考着来使用: URL路径 说明 /user-service/? 它可以匹配 /user-s

  • springboot整合redis进行数据操作(推荐)

    redis是一种常见的nosql,日常开发中,我们使用它的频率比较高,因为它的多种数据接口,很多场景中我们都可以用到,并且redis对分布式这块做的非常好. springboot整合redis比较简单,并且使用redistemplate可以让我们更加方便的对数据进行操作. 1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starte

  • Spring注入Date类型的三种方法总结

    Spring注入Date类型的三种方法总结 测试Bean: public class DateBean { private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } 方式1:利用SimpleDateFormat的构造方法注入 <?xml version="1.0&quo

  • python修改list中所有元素类型的三种方法

    修改list中所有元素类型: 方法一: new = list() a = ['1', '2', '3'] for x in a: new.append(int(x)) print(new) 方法二: a = ['1', '2', '3'] b = [int(x) for x in a] print(b) 方法三: a = ['1', '2', '3'] print(map(int, a)) 以上这篇python修改list中所有元素类型的三种方法就是小编分享给大家的全部内容了,希望能给大家一个参

  • 详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

    在用pandas包和numpy包对数据进行分析和计算时,经常用到DataFrame和array类型的数据.在对DataFrame类型的数据进行处理时,需要将其转换成array类型,是以下列出了三种转换方法. 首先导入numpy模块.pandas模块.创建一个DataFrame类型数据df import numpy as np import pandas as pd df=pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]}) 1.使用DataFra

  • java对象转换String类型的三种方法

    一.采用Object.toString()toString方法是java.lang.Object对象的一个public方法.在java中任何对象都会继承Object对象,所以一般来说任何对象都可以调用toString这个方法.这是采用该种方法时,常派生类会覆盖Object里的toString()方法.但是在使用该方法时要注意,必须保证Object不是null值,否则将抛出NullPointerException异常. 二.采用(String)Object 该方法是一个标准的类型转换的方法,可以将

  • C#、.Net中把字符串(String)格式转换为DateTime类型的三种方法

    方式一:Convert.ToDateTime(string) 复制代码 代码如下: Convert.ToDateTime(string) 注意:string格式有要求,必须是yyyy-MM-dd hh:mm:ss 方式二:Convert.ToDateTime(string, IFormatProvider) 复制代码 代码如下: DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo(); dtFormat

  • SpringBoot实现定时发送邮件的三种方法案例详解

    目录 一.发送邮件的三种方法 二.定时任务介绍 1.@EnableScheduling 2.@Scheduled 三.前期准备工作 1.登录QQ邮箱获取授权码 第一步:进入QQ邮箱 第二步:找到POP3/SMTP,并开启 第三步:复制授权码 2.pom.xml中的依赖 3.在全局配置文件application.properties添加邮件服务配置 四.操作 一.创建邮件发送任务管理的业务处理类SendEmailService 二.在test类中发送邮件 三.发送定时邮件 四.在项目启动类上添加基

  • SpringMVC统一异常处理三种方法详解

    这篇文章主要介绍了SpringMVC-统一异常处理三种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在 Spring MVC 应用的开发中,不管是对底层数据库操作,还是业务层或控制层操作,都会不可避免地遇到各种可预知的.不可预知的异常需要处理. 如果每个过程都单独处理异常,那么系统的代码耦合度高,工作量大且不好统一,以后维护的工作量也很大. 如果能将所有类型的异常处理从各层中解耦出来,这样既保证了相关处理过程的功能单一,又实现了异常信

  • 三种方法解决ASP.NET Core 6中的依赖项

    依赖性注入是一种技术,它允许我们注入一个特定类的依赖对象,而不是直接创建这些实例. 使用依赖注入的好处显而易见,它通过放松模块间的耦合,来增强系统的可维护性和可测试性. 依赖注入允许我们修改具体实现,而不必改变依赖于它们的依赖类型. ASP.NET Core 很重视依赖注入技术.ASP.NET Core 中内置的依赖注入提供功能模块,并不像 StructureMap 和 Ninject 等IoC(控制反转)容器那样功能丰富,但它速度快,易于配置,而且易于使用.我们可以使用它在 ASP.NET C

  • SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法

    properties配置文件如下: human.name=Mr.Yu human.age=21 human.gender=male 如何把properties里面的配置绑定到JavaBean里面,以前我们的做法如下: public class PropertiesUtil { public static void getProperties(Person person) throws IOException { Properties properties = new Properties();

  • 详解Spring Boot 访问Redis的三种方式

    目录 前言 开始准备 RedisTemplate JPA Repository Cache 总结 前言 最近在极客时间上面学习丁雪丰老师的<玩转 Spring 全家桶>,其中讲到访问Redis的方式,我专门把他们抽出来,在一起对比下,体验一下三种方式开发上面的不同, 分别是这三种方式 RedisTemplate JPA Repository Cache 开始准备 开始之前我们需要有Redis安装,我们采用本机Docker运行Redis, 主要命令如下 docker pull redis doc

随机推荐