直接上代码:
1,配置文件配置:
gxp:
info:
address: 127.0.0.1
port: 8080
fruits:
apple: red
banner: yellow
2:创建一个实体类,从这里获取配置信息映射
@Data
@ConfigurationProperties(prefix = "gxp")
public class FileProperties {
private final Info info = new Info();
private final Fruits fruits = new Fruits();
@Data
public static class Info {
private String address;
private String port;
}
@Data
public static class Fruits {
private String apple;
private String banner;
}
}
3,创建一个配置类
@Configuration
@EnableConfigurationProperties(FileProperties.class)
public class FileAutoConfigtration {
public FileProperties.Info info;
public FileProperties.Fruits fruits;
public FileAutoConfigtration(FileProperties customizProperties){
this.info = customizProperties.getInfo();
this.fruits = customizProperties.getFruits();
}
}
4,测试
@SpringBootTest
@RunWith(SpringRunner.class)
class Demo1ApplicationTests {
@Autowired
FileAutoConfigtration cusomizeAutoConfigtration;
@Test
void contextLoads() {
System.out.println(cusomizeAutoConfigtration.info.getAddress());
System.out.println(cusomizeAutoConfigtration.fruits.getApple());
}
}
依赖配置:
lombok依赖:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-maven-plugin --> <dependency> ? ? <groupId>org.projectlombok</groupId> ? ? <artifactId>lombok-maven-plugin</artifactId> ? ? <version>1.18.18.0</version> ? ? <scope>provided</scope> </dependency>
@Runwith的依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
@EnableConfigurationProperties注解作用,加载标注@ConfigurationProperties注解的类,使其注入到spring容器,这是为什么这里不需要注入容器中,因为@EnableConfigurationProperties注解已经帮我们做了。
不懂评论区询问,看见回。
|