Spring对资源的加载

03-07 1959阅读

Spring对资源的加载(Properties)

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
public class PropertiesResourceLoader implements ResourceLoaderAware {
    /**
     * 文件的相对路径 -  resources(classPatch)文件加下
     */
    private static final String propertiesFilePath = "/META-INF/msg.properties";
    /**
     * 编码格式
     */
    private static final String ENCODE = "UTF-8";
    private ResourceLoader resourceLoader;
    public PropertiesResourceLoader() {
        this.resourceLoader = getResourceLoader();
    }
    /**
     * @return 返回读取到的文件数据
     */
    public Properties getProperties() {
        ResourceLoader resourceLoader = getResourceLoader();
        Resource resource = resourceLoader.getResource(propertiesFilePath);
        EncodedResource encodingResource = new EncodedResource(resource,ENCODE);
        try (Reader reader = encodingResource.getReader()){
            Properties properties = new Properties();
            properties.load(reader);
            return properties;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private ResourceLoader getResourceLoader() {
        return this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader();
    }
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    public static void main(String[] args) {
        PropertiesResourceLoader resourceLoader = new PropertiesResourceLoader();
        Properties properties = resourceLoader.getProperties();
        // 文件中的内容 name=hello 获取 name 值
        String value = properties.getProperty("name");
        System.out.println(value);
    }
}
Spring对资源的加载
(图片来源网络,侵删)
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]