16、在bean中获取Resource

来源:互联网 发布:西安电子科技大学网络与继续教育 编辑:程序博客网 时间:2024/06/04 00:38

本章我们讲如何在Bean中获取Resource,就是在Spring中如何向我们的Bean注入Resource。下面我们来实现这个功能。

编写Bean

这里我们实现一个工具类,用于读取Properties文件并提供一个方法用于根据key获取对应的值。

package com.codestd.springstudy.resource;import java.util.Properties;import org.springframework.beans.factory.InitializingBean;import org.springframework.core.io.Resource;public class PropertiesUtils implements InitializingBean{    private Properties properties;    private Resource resource;    public void setResource(Resource resource) {        this.resource = resource;    }    @Override    public void afterPropertiesSet() throws Exception {        properties = new Properties();        properties.load(this.resource.getInputStream());    }    public String get(String key){        return (String) this.properties.get(key);    }}

Properties文件

spel/setup.properties

system.name=spel

配置Bean

<bean id="propertiesUtils" class="com.codestd.springstudy.resource.PropertiesUtils">    <property name="resource" value="classpath:spel/setup.properties"/></bean>

测试

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"classpath:resource/applicationContext.xml"})public class PropertiesUtilsTest {    @Autowired    private PropertiesUtils propertiesUtils;    @Test    public void testGet() {        String value = this.propertiesUtils.get("system.name");        assertEquals("spel", value);    }}
2 0