---
title: "@value 注解设置默认值"
author: "TimerBin"
date: "2016-09-24T10:32:39Z"
tags: []
categories: ["开源软件"]
slug: "value"
draft: false
lastmod: "2016-09-24T10:32:39Z"
id: 2326570
url: "https://timerbin.iteye.com/blog/2326570"
---

在使用spring3.0后，看到了它新增的实用@value注解，一下整理下@value注解设置默认值的方法。

 

首先需要在spring容器中引入properties文件，例子如下所示：

 

```
<bean id="propertyConfigurer"
	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:ttt.properties</value>
			<value>classpath:timerbin.properties</value>
		</list>
	</property>
	<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
```

 timerbin.properties

 

 

```
timer.userAge=22
```

 

 

一、在java代码中使用properites中配置的值

 

 

```
@Value("${timer.userAge}")
private int userAge;
```

 

 

此时定义的userAge属性的类需要使用注解加载到spring容器中。

 

 

二、@Value 注解设置默认值

 

```
@Value("${timer.userAge:22}")
private int userAge;
```

 当未在properties中查找到timer.userAge时会将22赋值给userAge属性