您的位置:首页 > 编程语言 > Java开发

SpringBoot yml属性自动注入

2018-03-31 22:43 477 查看

SpringBoot yml属性自动注入

本文讲的是如何把一个yml文件中自定义的属性集合映射到一个类上

1.自定义yml 内容

// 以微信的配置为例
weixin:
appid: xxxxxxxxx
appSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
apiSecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
grantType: authorization_code


2.向spring注册组件类

@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "weixin")
public class WeixinProperties {

private String
appid,
appSecret,
apiSecret,
grantType;

}


3.添加注册依赖

// 如果不添加注册依赖,@ConfigurationProperties IDEA会报错,找不到属性
// 依赖添加好之后,maven reimport更新依赖
// 鼠标点击组件的字段,按住Ctrl可以导航到yml中定义的字段中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>


4.注入组件

@Data
@NoArgsConstructor
@AllArgsConstructor
@Configuration
@SuppressWarnings(IDEWarnType.ALL)
public class WeixinConfig {

// 自动注入组件
@Autowired
private WeixinProperties weixin;
4000

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: