有时候,我们需求在application.yml获得application.properties自定义属性。如何实现呢?
配置步骤
第一步:在pom.xml导入包或者开发工具选择该依赖包
<!--支持自定义属性-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
第二步:编写自定义属性类
//ftp.client.server,设置前缀,ignoreInvalidFields = true,属性是非必须的
@ConfigurationProperties(prefix = "com.springboot",ignoreUnknownFields = false)
public class CustomProperties {
private int id;
private String username;
private String password;
//补全get、set
}
第三步:在入口类启动支持自定义属性功能
@SpringBootApplication
@EnableConfigurationProperties({CustomProperties.class}) //启动自定义配置
public class Application {
public static void main(String[] args) {
SpringApplication.run(EgoManagerApplication.class, args);
}
}
第四步:配置文件
applicaiton.properties调用##配置自定义参数
com..springboot.id=1001
com..springboot.username=zhangsan
com..springboot.password=123
第五步:在controller或者service层使用@Value注解调用
@RestController
public class UserController {
@Value("${com.springboot.username}")
private String username;
@GetMapping("/hello")
public String hello(){
return "自定义属性:"+username;
}
}