0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Spring Bootで外部properties読み込み

Last updated at Posted at 2023-06-24

ファイルの階層

image.png

ソース

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?