Springの@PropertySourceと@Valueをつかってみる


## はじめに

Springframeworkの@PropertySource、@Valueアノテーションを使って、プロパティファイルから設定を取得する方法を記述します。

## 環境

* jdk 1.8
* Maven 3.3
* Springframework 4.2.1.RELEASE
* JUnit 4.21

## Mavenの設定

pom.xml

```xml:pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>sample</groupId>
  <artifactId>spring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.2.1.RELEASE</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

```

## プロパティファイルから設定を取得する

* Bean

```Java:sample.spring.beans.SampleBean.java
package sample.spring.beans;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SampleBean {

	@Value("${sample.name}")
	private String name;

	@Value("${sample.age}")
	private int age;

	public String getMessage() {
		return String.format("Hello! My name is %s. I'm %d years old.", name, age);
	}

}
```

* JavaConfig

```Java:sample.spring.AppConfig.java
package sample.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan
@PropertySource(value = {"classpath:beans.properties"})
public class AppConfig {

	@Bean
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}

}
```

* プロパティファイル

```properties:beans.properties
sample.name = spring
sample.age = 11
```

* 動作確認用

```Java:sample.spring.beans.SampleBeanTest.java
package sample.spring.beans;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import sample.spring.AppConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class SampleBeanTest {

	@Autowired
	private SampleBean sampleBean;

	@Test
	public void greet() {
		System.out.println(sampleBean.getMessage());
	}

}
```

* コンソール出力

```
Hello! My name is spring. I'm 11 years old.
```

## おまけ

### Environmentを利用して取得する場合

* Bean

```Java:sample.spring.env.beans.SampleBean.java
package sample.spring.env.beans;

public class SampleBean {

	private String name;

	private int age;

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getMessage() {
		return String.format("Hello! My name is %s. I'm %d years old.", name, age);
	}

}
```

* JavaConfig

```Java:sample.spring.env.AppConfig.java
package sample.spring.env;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import sample.spring.env.beans.SampleBean;

@Configuration
@PropertySource(value = {"classpath:beans.properties"})
public class AppConfig {

	@Autowired
	private Environment env;

	@Bean
	public SampleBean sampleBean() {
		SampleBean bean = new SampleBean();
		bean.setName(env.getProperty("sample.name"));
		bean.setAge(Integer.valueOf(env.getProperty("sample.age")));
		return bean;
	}
}
```

* 動作確認用

```Java:sample.spring.env.beans.SampleBeanTest.java
package sample.spring.env.beans;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import sample.spring.env.AppConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class SampleBeanTest {

	@Autowired
	private SampleBean sampleBean;

	@Test
	public void greet() {
		System.out.println(sampleBean.getMessage());
	}

}
```

* コンソール出力

```
Hello! My name is spring. I'm 11 years old.
```


## 参考
* Springframewrk
 * [6.13. Environment abstraction / 6.13.4 @PropertySource] (http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#__propertysource)
 * [Annotation Type PropertySource] (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html)
 * [Annotation Type Value] (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html)
 * [Interface Environment] (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/Environment.html)
* Maven
 * [Setting the -source and -target of the Java Compiler] (https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html)