欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring注入值到Bean的三种方式

程序员文章站 2023-11-29 12:49:22
在spring中,有三种方式注入值到 bean 属性。 正常的方式 快捷方式 “p” 模式 新建一个user类,它包含username和password两个...

在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配置文件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。