自定義配置
application.yml
hara:
name: hanaii
password: 123456
通過@Value
注解和${參數(shù)名}
來獲取
package fun.hara.demo.hello.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Controller
public class HelloController {
/* 獲取自定義配置 */
@Value("${hara.name}")
String username;
@Value("${hara.password}")
String password;
@RequestMapping("/hello")
public void hello(HttpServletResponse response) throws Exception{
System.out.println(username);
System.out.println(password);
}
}
類型安全的配置
使用@Value
注入每個自定義配置在項目中顯得很麻煩蔬啡,當自定義屬性很多時需要注入很多次
Spring Boot 還提供了基于類型安全的配置方式,通過@ConfigurationProperties
。
application.yml
hara:
name: hanaii
password: 123456
通過@ConfigurationProperties
配置參數(shù)前綴君珠,參數(shù)值會自動注入同名字段。(必須提供setter
方法)
package fun.hara.demo.hello.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Controller
@ConfigurationProperties("hara")
public class HelloController {
private String name;
private String password;
@RequestMapping("/hello")
public void hello(HttpServletResponse response) throws Exception{
System.out.println(name);
System.out.println(password);
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
}