Spring注入值到Bean的三種方式
在Spring中,有三種方式注入值到 bean 屬性。
正常的方式
快捷方式
“p” 模式
新建一個User類,它包含username和password兩個屬性,現(xiàn)在使用spring的IOC注入值到該bean。
package com.example.pojo; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username= username; } public String getPassword() { return type; } public void setPassword(String password) { this.password= password; } }
1.正常方式
在一個“value”標簽注入值,并附有“property”標簽結束。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="user" class="com.example.User"> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> </beans>
2.快捷方式
注入值“value”屬性。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="user" class="com.example.User"> <property name="username" value="scott" /> <property name="password" value="tiger" /> </bean> </beans>
3. “p” 模式
通過使用“p”模式作為注入值到一個屬性。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="user" class="com.example.User" p:username="scott" p:password="tiger" /> </beans>
記住聲明 xmlns:p=”http://www.springframework.org/schema/p" 在Spring XML bean配置文件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot使用AOP實現(xiàn)日志記錄功能詳解
這篇文章主要為大家介紹了SpringBoot使用AOP實現(xiàn)日志記錄功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07Java中的異常處理(try,catch,finally,throw,throws)
本文主要介紹了Java中的異常處理,文章主要介紹的異常處理包括5個關鍵字try,catch,finally,throw,throws,更多詳細內容需要的朋友可以參考一下2022-06-06SpringBoot使用Maven實現(xiàn)多環(huán)境配置管理
軟件開發(fā)中經(jīng)常有開發(fā)環(huán)境、測試環(huán)境、生產(chǎn)環(huán)境,而且一般這些環(huán)境配置會各不相同,本文主要介紹了SpringBoot使用Maven實現(xiàn)多環(huán)境配置管理,感興趣的可以了解一下2024-01-01Docker搭建前端Java的開發(fā)環(huán)境詳解
相信每個人入職第一天就是搭建本地開發(fā)環(huán)境,因為我司用的是java,看見了多年不見的eclipse的圖標出現(xiàn)我的電腦上,我是難過的。后來知道并不是我一個人有此感受。這篇文章是為了解決前后端開發(fā)沒有徹底分離的坑,詳細的給大家介紹了利用Docker搭建前端Java的開發(fā)環(huán)境。2016-10-10