我自己的使用环境
spring版本:3.2.4.RELEASE
1,在项目的资源文件夹下建立配置文件config.properties,文件内容为:
#oss
ossimgCdnIp=thisistestparam
2,在spring的xml配置文件中添加配置。我的xml配置文件命名为sysBasex.xml
<!-- 打开注解驱动 -->
<context:annotation-config/>
<!-- spring的属性加载器,加载properties文件中的属性 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:config.properties</value>
<value>classpath*:platweb_config.properties</value>
</list>
</property>
<property name=”fileEncoding” value=”utf-8″ />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
<!-- 如果不想在xml文件中配置bean,可以给类加上spring组件注解,只需配置下spring的扫描器就可以实现bean的自动载入 -->
<context:component-scan base-package="com.vve.common"/>
3,
建立配置类
ConfigProperties.Java
的内容为如下。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;
//添加注解@Component,把类纳入进spring容器中管理
@Component("mallconfigProperties")
public class ConfigProperties {
//@Value注解中使用${key},取出key对应的value
@Value("${ossimgCdnIp}")
private String ossimgCdnIp;//经过CDN加速的图片地址
public String getOssimgCdnIp() {
return ossimgCdnIp;
}
public void setOssimgCdnIp(String ossimgCdnIp) {
this.ossimgCdnIp = ossimgCdnIp;
}
//测试用例
public static void main(String[] args) throws InterruptedException {
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.setValidating(false);
context.load("classpath*:sysBase.xml");
context.refresh();
ConfigProperties userService = context.getBean(ConfigProperties.class);
System.out.println(userService.getOssimgCdnIp());
context.close();
}
}
4,在业务类中 ValueIndexController 中调用配置类
@Controller
@RequestMapping("/valueindex/")
@SessionAttributes({"_mall", "_station", "_mallAdmin"})
public class ValueIndexController{
@Autowired
ConfigProperties configProperties;
}
(以上内容如有错误,欢迎指正)