ファイルの階層
ソース
some.properties
test01=HOGE
TEST02=22
application.properties
name="takeshi"
ReadProperties.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
// lombookの機能、ゲッターセッターtostring等をいい感じに作っといてくれる
@Data
@Component
@PropertySource("classpath:some.properties")
public class ReadProperties.java {
@Value("${name}")
private String name;
@Value("${test01}")
private String TEST01;
@Value("${TEST02}")
private String TEST02;
}
SpringBootDemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringBootDemoApplication.class, args);
ReadProperties bean = context.getBean(ReadProperties.class);
System.out.println(bean.toString());
context.close();
}
}
実行結果
ReadProperties(name="takeshi", TEST01=HOGE, TEST02=22)
Environmentを使って取得するパターン
ReadProperties.java
package com.example.demo;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import lombok.Data;
// lombookの機能、ゲッターセッターtostring等をいい感じに作っといてくれる
@Data
@Component
@PropertySource("classpath:some.properties")
public class ReadProperties {
private final Environment env;
// @Value("${name}")
private String name;
// @Value("${test01}")
private String TEST01;
// @Value("${TEST02}")
private String TEST02;
public void showProperties() {
System.out.println(env.getProperty("name"));
System.out.println(env.getProperty("test01"));
System.out.println(env.getProperty("TEST02.a"));
}
}
some.properties
test01=HOGE
TEST02.a=22
実行結果
"takeshi"
HOGE
22