Spring注入值到Bean的三种方式
在Spring中,有三种方式注入值到 bean 属性。
正常的方式
快捷方式
“p” 模式
新建一个User类,它包含username和password两个属性,现在使用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配置文件。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
IDEA2022.1创建maven项目规避idea2022新建maven项目卡死无反应问题
这篇文章主要介绍了IDEA2022.1创建maven项目规避idea2022新建maven项目卡死无反应问题,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-08-08SpringCloud Finchley Gateway 缓存请求Body和Form表单的实现
在接入Spring-Cloud-Gateway时,可能有需求进行缓存Json-Body数据或者Form-Urlencoded数据的情况。这篇文章主要介绍了SpringCloud Finchley Gateway 缓存请求Body和Form表单的实现,感兴趣的小伙伴们可以参考一下2019-01-01java组件commons-fileupload文件上传示例
这篇文章主要为大家详细介绍了java组件commons-fileupload实现文件上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-10-10jenkins+maven+svn自动部署和发布的详细图文教程
Jenkins是一个开源的、可扩展的持续集成、交付、部署的基于web界面的平台。这篇文章主要介绍了jenkins+maven+svn自动部署和发布的详细图文教程,需要的朋友可以参考下2020-09-09Java Runnable和Thread实现多线程哪个更好你知道吗
这篇文章主要为大家详细介绍了Java Runnable和Thread实现多线程哪个更好,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助<BR>2022-03-03
最新评论