Spring注入值到Bean的三种方式

网友投稿 193 2023-05-03


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 jZWHxusername;

}

public void setUsername(String username) {

this.username= username;

}

public String getPassword() {

return type;

}

public void setPassword(String password) {

this.password= password;

}

}

1.正常方式

在一个“value”标签注入值,并附有“property”标签结束。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

scott

tiger

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

scott

tiger

2.快捷方式

注入值“value”属性。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

3. “p” 模式

通过使用“p”模式作为注入值到一个属性。

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

p:username="scott" p:password="tiger" />

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:p="http://springframework.org/schema/p"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-2.5.xsd">

p:username="scott" p:password="tiger" />

p:username="scott" p:password="tiger" />

记住声明 xmlns:p=”http://springframework.org/schema/p" 在Spring XML bean配置文件。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java Runnable接口创建线程
下一篇:java中的数学计算函数的总结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~