SpringBootで@PropertySourceと@ImportResourceおよび@Bean
5979 ワード
@PropertySource
*.properties
ファイルのみをロードでき、yaml
ファイル新しい
user.properties
user.nickname=
user.age=19
user.sex=
user.maps.weight=70
user.maps.height=170
user.address.addr=
UserBean
@Component
@PropertySource(value = {"classpath:user.properties"})
@ConfigurationProperties(prefix = "user")
public class User {
private String nickname;
private Integer age;
private char sex;
private Map maps;
private Address address;
...
}
@ImportResource
Spring
のプロファイルをインポートし、プロファイルの内容を有効にするSpringBootで作成したSpringプロファイルは自動認識できません
メインコンフィギュレーションクラスに
@ImportResource
を追加@ImportResource(locations = {"classpath:beans.xml"})
SpringBootコンテナにコンポーネントを追加する方法
1、構成クラス==Springプロファイルは
@Configuration
で宣言2、
@Bean
を使用してコンテナにコンポーネントを追加し、コンポーネントidはデフォルトで方法名である例
package com.atgenee.demo.service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Hello {
@Bean
public Hello helloService() {
System.out.println(" ");
return new Hello();
}
}
テスト
package com.atgenee.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceApplicationTests {
// @Autowired
// private Hello hello;
//
// @Test
// public void hello() {
// hello.helloService();
// }
@Autowired
private ApplicationContext ioc;
@Test
public void hello() {
ioc.getBean("helloService");
}
}
ご注意ください
コンフィギュレーションクラスに@Bean注記が追加されている場合、コンフィギュレーションクラスのメソッド名はクラス名と同じではありません.つまり、上のHelloクラスではhello()のメソッドを定義できません.そうしないと、エラーが発生します.
カスタムファクトリによるカスタムyamlファイルのロード
新しいcatを作成します。ymlファイル
cat:
age: 3
height: 20
weight: 5
工場クラス
package com.atgenee.demo.factory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
新しいコンフィギュレーションクラスCat,@PropertySource注記と組み合わせて使用
package com.atgenee.demo.config;
import com.atgenee.demo.factory.YamlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:cat.yml")
@ConfigurationProperties(prefix = "cat")
public class Cat {
private int age;
private Double weight;
private Double height;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
@Override
public String toString() {
return "Cat{" +
"age=" + age +
", weight=" + weight +
", height=" + height +
'}';
}
}
Catテストクラス
package com.atgenee.demo;
import com.atgenee.demo.config.Cat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CatApplicationTests {
@Autowired
private Cat cat;
@Test
public void hei() {
System.out.println(cat);
}
}
コンソール出力
Cat{age=3, weight=5.0, height=20.0}
cat:
age: 3
height: 20
weight: 5
package com.atgenee.demo.factory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
package com.atgenee.demo.config;
import com.atgenee.demo.factory.YamlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:cat.yml")
@ConfigurationProperties(prefix = "cat")
public class Cat {
private int age;
private Double weight;
private Double height;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
@Override
public String toString() {
return "Cat{" +
"age=" + age +
", weight=" + weight +
", height=" + height +
'}';
}
}
package com.atgenee.demo;
import com.atgenee.demo.config.Cat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CatApplicationTests {
@Autowired
private Cat cat;
@Test
public void hei() {
System.out.println(cat);
}
}
Cat{age=3, weight=5.0, height=20.0}