源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Spring注入值到Bean的三种方式

  • 时间:2022-12-26 20:23 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Spring注入值到Bean的三种方式
在Spring中,有三种方式注入值到 bean 属性。 [b]正常的方式 快捷方式 “p” 模式[/b] 新建一个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;
 }
}
[b]1.正常方式[/b] 在一个“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>
[b]2.快捷方式[/b] 注入值“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>

[b]3. “p” 模式[/b]  通过使用“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>

 记住声明[b]xmlns:p=”http://www.springframework.org/schema/p"[/b] 在Spring XML bean配置文件。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部