Spring中的注解@Value("#{}")與@Value("${}")的區(qū)別介紹
1 @Value("#{}") SpEL表達式
@Value("#{}") 表示SpEl表達式通常用來獲取bean的屬性,或者調(diào)用bean的某個方法。當然還有可以表示常量
@RestController
@RequestMapping("/login")
@Component
public class LoginController {
@Value("#{1}")
private int number; //獲取數(shù)字 1
@Value("#{'Spring Expression Language'}") //獲取字符串常量
private String str;
@Value("#{dataSource.url}") //獲取bean的屬性
private String jdbcUrl;
@Autowired
private DataSourceTransactionManager transactionManager;
@RequestMapping("login")
public String login(String name,String password) throws FileNotFoundException{
System.out.println(number);
System.out.println(str);
System.out.println(jdbcUrl);
return "login";
}
} 當bean通過@Value(#{""}) 獲取其他bean的屬性,或者調(diào)用其他bean的方法時,只要該bean (Beab_A)能夠訪問到被調(diào)用的bean(Beab_B),即要么Beab_A 和Beab_B在同一個容器中,或者Beab_B所在容器是Beab_A所在容器的父容器。(拿我上面貼出來的代碼為例在springMvc項目中,dataSource這個bean一般是在springContext.xml文件中申明的,而loginController這個bean一般是在springMvc.xml文件中申明的,雖然這兩個bean loginController和dataSource不在一個容器,但是loginController所在容器繼承了dataSource所在的容器,所以在loginController這個bean中通過@Value("#{dataSource.url}")能夠獲取到dataSource的url屬性)。
2 @Value("${}")
通過@Value("${}") 可以獲取對應屬性文件中定義的屬性值。假如我有一個sys.properties文件 里面規(guī)定了一組值: web.view.prefix =/WEB-INF/views/
在springMvc.xml文件中引入下面的代碼既即以在 該容器內(nèi)通過@Value("${web.view.prefix}")獲取這個字符串。需要指出的是,如果只在springMvc.xml引入下面代碼,只能在springMvc.xml文件中掃描或者注冊的bean中才能通過@Value("${web.view.prefix}")獲取這個字符串,其他未在springMvc.xml掃描和定義的bean必須在相應的xml文件中引入下面代碼才能使用@Value("${}”)表達式
- <!-- 加載配置屬性文件 -->
- <context:property-placeholder
- ignore-unresolvable="true" location="classpath:sys.properties" />
然后再controller文件中通過下面代碼即可獲取“”/WEB-INF/views/“”這個字符串
- @Value("${web.view.prefix}")
- private String prefix;
到此這篇關于Spring中的注解@Value(“#{}“)與@Value(“${}“)的區(qū)別到底是什么?的文章就介紹到這了,更多相關Spring注解@Value(“#{}“)與@Value(“${}“)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
synchronized背后的monitor鎖實現(xiàn)詳解
這篇文章主要為大家介紹了synchronized背后的monitor鎖實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
詳解SpringMVC @RequestBody接收Json對象字符串
這篇文章主要介紹了詳解SpringMVC @RequestBody接收Json對象字符串,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
SpringBoot整合TKMyBatis實現(xiàn)單表增刪改查操作
據(jù)說tk.mybatis能夠讓我不寫sql代碼就可以所有單表操作問題,作為熱愛偷懶的我,怎么能放過這種機會。talk is cheap, show me the code。趕緊搞個例子爽一把先2023-01-01
使用Springboot實現(xiàn)健身房管理系統(tǒng)
這篇文章主要介紹了使用Springboot如何實現(xiàn)健身房管理系統(tǒng),希望對你有所幫助2021-07-07

