Spring load properties file and MessageFormat

During yesterday's code review, learn another way to load properties file by using Spring. Spring is so powerful, I love it!

I found there are two ways to do that:

1. use <util:properties>

1) Define your properties file test.properties

username=test

2) you need to define that in you applicationContext.xml to load the properties file.

<util:properties id="myProps" location="classpath:*.properties />

3) In you controller or other spring bean classes, you can use

@Controller
public class MyController{

	@Value("#myprops[username]")
	private String username;

}
I didn't test it. Just searched online. 

2. use context:property-placeholder

1) test.properties

username=test
2) Define context:property-placeholder in your context.xml.
<context:property-placeholder location="classpath*:youbar*.properties"
		ignore-resource-not-found="false" local-override="false"
		ignore-unresolvable="false" />
Here I ran into a problem that I can't place the code above into applicationContext.xml, I have another youbarportlet.xml. The applicationContext.xml is loaded from web.xml from context-param, the second is like spring-servlet.xml.

I haven't entirely sure about the problem.

3) Access property through @Value annotation

@Controller
public class MyController{

	@Value("${username}")
	private String username;

}


Then you can use the value anywhere in your controller. It's really convenient, right?

In case, you want to customize the value of properties.

greeting=Welcome, firstname lastname

firstname and lastname can't be defined in the properties. In this case, you need to use placeholder and then you MessageFormat to replace them.

greeting=Welcome, {0} {1}!
@Controllerpublic class MyController{
    @Value("${greeting}")
    private String greeting;

    public void renderView(){
        String newGreeting = MessageFormat.format(greeting, "test", "test");
    }
}

Then you'll see the value of newGreeting = Welcome, test test!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值