首先value注解的使用
controller代码
package com.quan.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.quan.service.HuaweiService;
import com.quan.service.HuaweiService2;
/**
* @author yangquan
*/
@RestController
@RequestMapping("/controller")
public class HuaweiController {
@Autowired
private HuaweiService huaweiService;
@Autowired
private HuaweiService2 huaweiService2;
@RequestMapping("/test")
public void test(){
huaweiService.test();
}
@RequestMapping("/test2")
public void test2(){
huaweiService2.test();
}
}
service代码
package com.quan.service.impl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import com.quan.service.HuaweiService;
// @ConfigurationProperties(
// prefix = "huawei"
// )
@Service
public class HuaweiServiceImpl implements HuaweiService {
/**用户在华为开发者联盟申请Push服务获取的服务参数*/
// private static String appId = "12345678";
@Value("${huawei.app-id}")
private String appId;
/**用户在华为开发者联盟申请Push服务获取的服务参数*/
// private static String appSecret = "appSecret";
@Value("${huawei.app-secret}")
private String appSecret;
@Override
public void test() {
System.out.println(appId+" "+appSecret);
}
}
其次ConfigurationProperties注解的使用
service代码
package com.quan.service.impl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import com.quan.service.HuaweiService;
import com.quan.service.HuaweiService2;
import lombok.Data;
/**
* @author yangquan
*/
@Data
// @Configuration
@ConfigurationProperties(prefix="hw")
@Service
public class HuaweiServiceImpl2 implements HuaweiService2 {
/**用户在华为开发者联盟申请Push服务获取的服务参数*/
// private static String appId = "12345678";
private String appId;
/**用户在华为开发者联盟申请Push服务获取的服务参数*/
// private static String appSecret = "appSecret";
private String appSecret;
@Override
public void test() {
System.out.println(appId+" "+appSecret);
}
}
yml配置文件
server:
port: 8802
huawei:
app-id: 123
app-secret: 123
hw:
app-id: 234
app-secret: 234
请求路径
http://localhost:8802/controller/test2
http://localhost:8802/controller/test2
运行结果
网上一种说法使用ConfigurationProperties这个注解需要添加以下依赖
<!-- 支持 @ConfigurationProperties 注解 -->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>-->
我这里没有添加也是可以获取到配置文件中的值的。大家可以自行决定
欢迎加入技术群聊
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!!