前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring------自动化装配Bean(三) 一、打开application.xml

Spring------自动化装配Bean(三) 一、打开application.xml

作者头像
用户2417870
发布2019-09-18 11:39:49
4900
发布2019-09-18 11:39:49
举报
文章被收录于专栏:g歌德ag歌德a

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

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

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

一、打开application.xml

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

代码语言:javascript
复制
<?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>

二、测试代码

代码语言:javascript
复制
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();
    
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、打开application.xml
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档