Spring------自动化装配Bean(三)

上一篇是基于java手动装配bean的实现,这一篇将通过xml手动装配bean来实现。

xml配置相对于java配置有点:

  1. xml配置更加快捷
  2. 但不宜扩展

一、打开application.xml

  1、注释掉<context:component-scan base-package="soundsystem"></context:component-scan>

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <!--  <context:component-scan base-package="soundsystem"></context:component-scan>-->
    <!-- 
        自动化的bean命名方式非常方便,但如果接下来要引用的话就会感觉被约束
        所以用id属性为每个bean创建自己的名字
     -->
    <bean id="cd" class="soundsystem.SgtPeppers"></bean>
    
    <bean id="cdPlayer" class="soundsystem.CDPlayer">
        <constructor-arg ref="cd"></constructor-arg>
    </bean>
</beans>

二、测试代码

  

package test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import soundsystem.CDPlayer;
import soundsystem.CompactDisc;
import soundsystem.MediaPlayer;
import soundsystem.SgtPeppers;

public class Test {
    public static void main(String[] args) {
    //基于java类中配置上下文
    //AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(soundsystem.JavaConfig2.class); 
    //基于xml配置上下文
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationContext.xml");
    MediaPlayer cd= (MediaPlayer) context.getBean("cdPlayer");
    cd.play();
//    MediaPlayer player=context.getBean(CDPlayer.class);
//    player.play();
    
    }
}

 

上一篇:NiceVieoPlayer 初次尝试


下一篇:使用MediaPlayer+Service完成音乐播放器