SPRING IN ACTION 第4版笔记-第二章Wiring Beans-005-<constructor-arg>和c-namespace

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPRING IN ACTION 第4版笔记-第二章Wiring Beans-005-<constructor-arg>和c-namespace相关的知识,希望对你有一定的参考价值。

1.

 1 package soundsystem;
 2 
 3 public class SgtPeppers implements CompactDisc {
 4 
 5   private String title = "Sgt. Pepper‘s Lonely Hearts Club Band";  
 6   private String artist = "The Beatles";
 7   
 8   public void play() {
 9     System.out.println("Playing " + title + " by " + artist);
10   }
11 
12 }

 

2.

 1 package soundsystem;
 2 import org.springframework.beans.factory.annotation.Autowired;
 3 
 4 public class CDPlayer implements MediaPlayer {
 5   private CompactDisc cd;
 6 
 7   @Autowired
 8   public CDPlayer(CompactDisc cd) {
 9     this.cd = cd;
10   }
11 
12   public void play() {
13     cd.play();
14   }
15 
16 }

 

一、-<constructor-arg>

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">

  <bean id="compactDisc" class="soundsystem.SgtPeppers" />
        
  <bean id="cdPlayer" class="soundsystem.CDPlayer">
    <constructor-arg ref="compactDisc" />
  </bean>

</beans>

 

二、c-namespace(3.0开始有)

(1)指定参数名称

 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"
 4   xmlns:c="http://www.springframework.org/schema/c"
 5   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 6 
 7   <bean id="compactDisc" class="soundsystem.SgtPeppers" />
 8         
 9   <bean id="cdPlayer" class="soundsystem.CDPlayer"
10         c:cd-ref="compactDisc" />
11 
12 </beans>

技术分享

(2)指定参数顺序

<bean id="cdPlayer" class="soundsystem.CDPlayer"
c:_0-ref="compactDisc" />

(3)如查构造函数只有一个参数,则可以连顺序都不用指定

<bean id="cdPlayer" class="soundsystem.CDPlayer"
c:_-ref="compactDisc" />

 

以上是关于SPRING IN ACTION 第4版笔记-第二章Wiring Beans-005-<constructor-arg>和c-namespace的主要内容,如果未能解决你的问题,请参考以下文章

SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-008-SpEL介绍

SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@ScopeProxyMode

SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-011-注入AspectJ Aspect

SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMappingmodel

SPRING IN ACTION 第4版笔记-第九章Securing web applications-004-对密码加密passwordEncoder

SPRING IN ACTION 第4版笔记-第四章Aspect-oriented Spring-001-什么是AOP