Spring PropertyEditor

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<property name="mapperLocations" value="classpath:mybatis/mapper/ms/*.xml" />
	<property name="typeAliasesPackage" value="cn.freemethod.to" />
	<property name="configLocation" value="classpath:mybatis/config.xml" />	
</bean>

        在使用Spring和MyBatis集成的時候,配置瞭如上所示的bean,這個bean對應的類是SqlSessionFactoryBean,這個類實現了FactoryBean,這裏不詳細介紹這個類,咱們只是看一看它的mapperLocations和configLocation兩個屬性。java

  圖1 SQLSessionFactoryBeanspring

       如上圖所示,咱們能夠看到 mapperLocations和configLocation兩個屬性是Resource類型,spring是怎樣處理的呢?怎樣把一個字符串轉換爲一個Resource類型的呢?這裏就要介紹一下PropertyEditor這個接口了。咱們仍是先來看一個例子在來看上面的問題。sql

       先來一個類,咱們仍是使用User這類吧:mybatis

public class User {
    private Integer id;

    private String name;

    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
    }
    

}

       UserPropertyEditor繼承PropertyEditorSupport,主要重寫了setAsText方法和getAsText方法。PropertyEditorSupport實現了PropertyEditor接口。app

import java.beans.PropertyEditorSupport;

import cn.freemethod.to.User;

public class UserPropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String[] fields = text.split(",");
        if(fields.length != 3)
            throw new IllegalArgumentException("User 屬性配置錯誤");
        User user = new User();
        try {
            int id = Integer.parseInt(fields[0]);
            user.setId(id);
        } catch (Exception e) {
            throw new IllegalArgumentException("User的屬性配置錯誤");
        }
        user.setName(fields[1]);
        user.setAddress(fields[2]);
        setValue(user);
    }

    @Override
    public String getAsText() {
        User user = (User) getValue();
        return user.toString();
    }

}

       配置文件,主要是把咱們自定義的UserPropertyEditor註冊到CustomerEditorConfigurer中這樣當Spring在處理配置文件的時候發現須要把對應的String類型轉換成對應類型就能夠是咱們註冊在 CustomerEditorConfigurer 的PropertyEditor了。ide

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="cn.freemethod.to.User" value="cn.freemethod.test.UserPropertyEditor" />
			</map>
		</property>
	</bean>
	
	
	<bean id="start" class="cn.freemethod.test.Start">
		<property name="user" value="1,tim,chengdu" />
	</bean>

</beans>

主類:測試

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.freemethod.to.User;

public class Start {
    
    private  User user;
    
    public static void main(String[] args) {
        
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
        Start start = (Start) context.getBean("start");
        System.out.println(start.user);
        
        
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    
}

測試結果:ui

圖2 測試結果this

       從測試結果能夠看到Spring利用UserPropertyEditor成功把特定的字符串類型轉換爲了User類型。spa

       一樣的道理,也能夠把字符串轉換爲Resource類型,Spring已經爲咱們提供了一個ResourceEditor類,因此咱們在SqlSessionFactoryBean中能夠把字符串配置轉換爲Resource類型。下面是ResourceEditor的源碼。

package org.springframework.core.io;

import java.beans.PropertyEditorSupport;
import java.io.IOException;

import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

public class ResourceEditor extends PropertyEditorSupport {

	private final ResourceLoader resourceLoader;

	private PropertyResolver propertyResolver;

	private final boolean ignoreUnresolvablePlaceholders;


	
	public ResourceEditor() {
		this(new DefaultResourceLoader(), null);
	}

	
	@Deprecated
	public ResourceEditor(ResourceLoader resourceLoader) {
		this(resourceLoader, null, true);
	}

	
	@Deprecated
	public ResourceEditor(ResourceLoader resourceLoader, boolean ignoreUnresolvablePlaceholders) {
		this(resourceLoader, null, ignoreUnresolvablePlaceholders);
	}

	
	public ResourceEditor(ResourceLoader resourceLoader, PropertyResolver propertyResolver) {
		this(resourceLoader, propertyResolver, true);
	}

	
	public ResourceEditor(ResourceLoader resourceLoader, PropertyResolver propertyResolver, boolean ignoreUnresolvablePlaceholders) {
		Assert.notNull(resourceLoader, "ResourceLoader must not be null");
		this.resourceLoader = resourceLoader;
		this.propertyResolver = propertyResolver;
		this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
	}


	@Override
	public void setAsText(String text) {
		if (StringUtils.hasText(text)) {
			String locationToUse = resolvePath(text).trim();
			setValue(this.resourceLoader.getResource(locationToUse));
		}
		else {
			setValue(null);
		}
	}


	protected String resolvePath(String path) {
		if (this.propertyResolver == null) {
			this.propertyResolver = new StandardEnvironment();
		}
		return (this.ignoreUnresolvablePlaceholders ? this.propertyResolver.resolvePlaceholders(path) :
				this.propertyResolver.resolveRequiredPlaceholders(path));
	}


	@Override
	public String getAsText() {
		Resource value = (Resource) getValue();
		try {
			return (value != null ? value.getURL().toExternalForm() : "");
		}
		catch (IOException ex) {
			return null;
		}
	}

}
相關文章
相關標籤/搜索