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
- 16、在bean中获取Resource
- 解决Jersey中使用@Resource注解无法获取bean
- 在servlet中获取spring Bean对象
- 在spring的bean中获取ServletContext
- 在spring的bean中获取ServletContext
- Spring:在bean中获取ServletContext
- 在spring的bean中获取servletcontext
- Spring在JAVA中获取bean
- Spring中注解@Bean、@Resource、@Component、@SpringStudy
- bean:resource
- Action中获取Bean
- jsp中获取bean
- 在自定义标签子类获取Spring中注册的bean
- 在jsp页面中获取Spring管理的Bean
- java-在应用中获取spring定义的bean
- 在servlet中获取spring管理的bean
- java-在应用中获取spring定义的bean
- AM使用指南:如何在Managed Bean中获取AM实例?
- 手机号码合法性
- Java中getBytes()方法--使用详解
- 欢迎使用CSDN-markdown编辑器
- 顺序表应用2:多余元素删除之建表算法
- SIFT算法的Matlab实现
- 16、在bean中获取Resource
- maven搭建ssm分模块框架 (myeclipse版) (二)
- introduce myself
- HElib 库如何使用?加密解密数据
- zy-题目总结
- poj 3069贪心~
- 17、Spring实战:利用AOP实现日志监控
- log4j-每天日志文件加日期后缀
- c++实验6-字符串操作