springboot配置注入(数据绑定)有两种方式。
第一种,使用@Value
- 首先,在
application.yml
中定义自己的数据。
# application.yml
server:
port: 8000
user:
nickname: Nicholas
password: Changeme@123
- 然后,新建package
controller
,在该package下新建类TestController
,内容如下:
package com.jepcc.example.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@Value("${user.nickname}")
private String name;
@Value("${user.password}")
private String password;
@GetMapping("/user")
public String getUser(){
return name+"'s password is "+ password;
}
}
- 最后,调用接口
http://localhost:8000/test/user
进行测试。
第二种,使用@ConfigurationProperties
- 首先,在
pom.xml
中引入专用于数据绑定的插件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 然后,新建package
config
,并在该package下新建类TestConfig
,如下:
package com.jepcc.example.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "user")
public class TestConfig {
private String nickname;
private String password;
}
- 再然后,修改
TestController
,如下:
package com.jepcc.example.controller;
import com.jepcc.example.config.TestConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestConfig testConfig;
@GetMapping("/user")
public String getUser(){
return testConfig.getNickname()+"'s password is "+testConfig.getPassword();
}
}
- 最后,调用接口:
http://localhost:8000/test/user
进行调试。