温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中如何将值注入到Bean中

发布时间:2020-11-25 16:49:03 来源:亿速云 阅读:197 作者:Leah 栏目:编程语言

这篇文章给大家介绍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配置文件。

关于Spring中如何将值注入到Bean中就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI