spring如何注入Date类型的属性

来源:互联网 发布:百分百营销软件流量 编辑:程序博客网 时间:2024/04/18 22:52
spring可以为属性注入基本类型的值,也可以注入一个bean。当想注入非基本类型的值就得用到属性编辑器。它一般用在类型无法识别,如日期等。


实现步骤为以下两步:


1)继承PropertyEditorSupport


2)重写其setAsText方法,text是配置文件中的值(也就是为bean注入的值),我们就是将这个text按照需求进行转换。


先看下没用属性编辑器的情况:




    public class MyDate {  
        private Date date;  
      
        public Date getDate() {  
            return date;  
        }  
      
        public void setDate(Date date) {  
            this.date = date;  
        }  
      
        public static void main(String[] args) {  
            ApplicationContext context = new FileSystemXmlApplicationContext(  
                    "classpath:com/pb/propertyeditor/applicationContext.xml");  
            MyDate date = (MyDate) context.getBean("md");  
            System.out.println(date.getDate());  
        }  
    }  


bean id="md" class="com.pb.propertyeditor.MyDate">
<property name="date">
<value>2011-1-1</value>
</property>
</bean>


发生异常:


Caused by: Java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found


发生异常,没有发现匹配的编辑器或转换器。




现在需要的就是定义一个属性编辑器,并在spring中加入



    public class CustomerProperty extends PropertyEditorSupport {  
        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();  
            }  
        }  
    }  




    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">   <!--配置一个自定义编辑器-->  
            <property name="customEditors"><span style="white-space:pre">     </span><!--需要编辑的属性类型,是一个map-->  
                <map>  
                    <entry key="java.util.Date">  
                        <bean class="com.pb.propertyeditor.CustomerProperty">  
                            <property name="format" value="yyyy-mm-dd" />  <!--注入需要转换的格式-->  
                        </bean>  
                    </entry>  
                </map>  
            </property>  
        </bean>  
      
        <bean id="md" class="com.pb.propertyeditor.MyDate">  
            <property name="date">  
                <value>2011-1-1</value>  
            </property>  
        </bean>  




输出结果:Sat Jan 01 00:01:00 CST 2011
0 0
原创粉丝点击