以下基於SpringBoot2.0+
@Value三種情況的用法。
$是去找外部配置的參數,將值賦過來
#是SpEL表達式,去尋找對應變量的內容
直接寫字符串就是將字符串的值注入進去
$例子:
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("${hx.name}")
private String name;
@GetMapping("getName")
public String getName(){
return this.name;
}
}
配置文件:
application.properties
server.port=9090
hx.name = Chinese
上面那段代碼中@Value("${hx.name}")
會將配置文件中hx.name對應的值設置到name變量中:
#例子:
package com.example.demo;
import lombok.Data;
import org.springframework.stereotype.Component;
@Component
@Data
public class Another {
private Integer id = 1;
private String name = "xxx";
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("#{another.name}")
private String str;
@GetMapping("getStr")
public String getStr(){
return this.str;
}
}
上面代碼中,將Another類的name屬性注入到了str變量中:
例子
另外還有一種情況:
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("hanxu")
private String name;
@GetMapping("getOth")
public String getOth(){
return this.name;
}
}
直接將hanxu這個值注入到了name中: