深入学习Spring框架之六属性注入

本文介绍了Spring框架中的依赖注入概念,并通过实例演示了如何使用XML配置文件进行属性值和对象属性的注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们以及知道怎么通过spring创建Bean对象了,但是我们清楚,一个类它不仅有属性还有一些特定的行为。那么专属于这些类的属性,在Sprin中我们将通过何种方式注入呢?

通常,JavaBean的属性是私有的,同时拥有一套存取器的方法,set和get方法。Spring就是借助属性的set方法来配置属性的值,这就是setter方式注入。

 


 
  1. /**

  2. * 运动员类,他有一个特殊的属性,该属性是对象

  3. * @author liuyc

  4. *

  5. */

  6. public class Player {

  7. private String name;

  8. private String age;

  9. private String subject;

  10. private Trainer trainer;

  11. public Player() {

  12. }

  13. public String getName() {

  14. return name;

  15. }

  16. public void setName(String name) {

  17. this.name = name;

  18. }

  19. public String getAge() {

  20. return age;

  21. }

  22. public void setAge(String age) {

  23. this.age = age;

  24. }

  25. public String getSubject() {

  26. return subject;

  27. }

  28. public void setSubject(String subject) {

  29. this.subject = subject;

  30. }

  31. public Trainer getTrainer() {

  32. return trainer;

  33. }

  34. public void setTrainer(Trainer trainer) {

  35. this.trainer = trainer;

  36. }

  37. }


 
  1. /**

  2. * 教练类

  3. * @author liuyc

  4. *

  5. */

  6. public class Trainer {

  7. private String name;

  8. private String age;

  9. private String subject;

  10. public Trainer() {

  11. }

  12. public String getName() {

  13. return name;

  14. }

  15. public void setName(String name) {

  16. this.name = name;

  17. }

  18. public String getAge() {

  19. return age;

  20. }

  21. public void setAge(String age) {

  22. this.age = age;

  23. }

  24. public String getSubject() {

  25. return subject;

  26. }

  27. public void setSubject(String subject) {

  28. this.subject = subject;

  29. }

  30. }


配置好XML文件:

 


 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  5.  
  6. <bean id="player" class="com.cm2easy.miki.example.chapter1.Player">

  7. <property name="name" value="林丹" />

  8. <property name="age" value="33" />

  9. <property name="subject" value="羽毛球" />

  10. <property name="trainer" ref="trainer" />

  11. </bean>

  12. <bean id="trainer" class="com.cm2easy.miki.example.chapter1.Trainer">

  13. <property name="name" value="李永波"/>

  14. <property name="age" value="54"/>

  15. <property name="subject" value="羽毛球"/>

  16. </bean>

  17. </beans>


    上述配置涉及了属性值是普通值和对象的属性注入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值