SpringMVC4.0使用properties file

今天结合看到的各位大神的微博以一篇关于springmvc 支持properties文件的文章
1.背景
spring 3.2开始支持配置注解的方式使用properties文件,4.0时支持多文件配置;这里以spring-4.0 为例介绍框架使用properties文件的方式。
2.引用方式
(一) 配置文件中使用:

//配置文件中必须引入响应的命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<context:property-placeholder location="classpath:db.properties" />
//使用实例:
 <property name="username" value="${db.username}" /> 

(二)采用(一)中的配置
在controller、service中引用

@Autowired //方式二,env里有系统自动注入的对象
private Environment env;//使用properties 中的变量
env.getproperty("db.username");

(三)采用将properties文件转换为系统对象的方式

//properties 
@Configuration
@PropertySource(value="classpath:db.properties")
public class Config {
    @Value(value="${db.username}")
    public String username;
    @Value(value="${db.password}")
    public String password;
    @Bean
    public static PropertySourcesPlaceholderConfigurer initProperty(){//必须的
        return new PropertySourcesPlaceholderConfigurer();
    }
}

在具体的controller 中使用注解引用
@Autowired
private Config c;

(四)采用配置文件注入的方式

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:db.properties" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
</bean>
//使用
@Value("#{configProperties['db.username']}")//注意是configProperties,#,{}等符号要对
private String username;

(五)采用util:properties

<util:properties location="classpath:db.properties" id="sys" /> 
//引用
@Value("#{sys['db.username']}")//注意是sys是对应的
private String un;

============实例下载==========链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值