zoukankan      html  css  js  c++  java
  • 【Spring 核心】装配Bean(一) 自动化装配

    Spring从两个角度实现自动化装配:组件扫描 (Spring自动发现应用上下文中所创建的bean)自动装配(autowiring)自动满足bean之间的依赖

    组件扫描:

    package test.soundsystem;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    import test.voice.Book;
    /*
     * 使用basePackageClasses,spring会自动扫描这些类所在的包,
     * 建议在包中写空标记接口,用来被扫描,有利于项目重构。
     * 
     * */
    @Configuration
    @ComponentScan(basePackageClasses={Book.class,CompactDisc.class})
    public class CDPlayerConfig {
    }

    接口:

    package test.soundsystem;
    
    public interface CompactDisc {
        void play();
    }

    实现类:

    package test.soundsystem;
    
    import javax.inject.Named;
    //Named 和 Component相似
    @Named
    public class SgtPeppers implements CompactDisc {
    
        private String title="Sgt. Pepper's Lonely Hearts Club Band";
        private String artist = "The Beatles";
        public void play() {
            System.out.println("Playing "+title+" by "+artist);
        }
    }

    测试类:

    package test.soundsystem;
    
    import javax.inject.Inject;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import test.voice.Book;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=CDPlayerConfig.class)
    public class CDPlayerTest {
        @Autowired
        private CompactDisc cd;
        
        @Inject
        private Book book;
        
        @Test
        public void cdShouldNotBeNull(){
            cd.play();
            book.read();
        }
    }


  • 相关阅读:
    【前端开发】git常见使用命令行,含git提交不交叉rebase操作方法
    【前端开发】vue项目版本提交日志插件changelog
    【git可视化】git可视化工具
    【node爬虫】简单的node爬虫实例教程
    【前端开发】常见的安全攻击
    计算机网络基础知识(待补充)
    大数据生态圈的一致性
    Android Stdio部分配置
    MySQL单机上多实例安装
    MySQL Replication
  • 原文地址:https://www.cnblogs.com/zhengwenqiang/p/6804619.html
Copyright © 2011-2022 走看看