zoukankan      html  css  js  c++  java
  • 【Spring】装配Bean 组件扫描

    实现自动装配需要用注解:注解分为 spring规范和java规范 ,java规范需要引入javax.inject 包 ,使用maven,直接引入。

    从中可以看到 @Named @Inject属于java规范,@Component  @Autowired @Resource属于spring注解

    @Named大致等效于@Component 而@Inject和@Autowired也相似,但是@Inject要强制注入,@Autowired(required=false)可以选择略过不报异常





    实例:

    1.写个bean接口

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

    2.实现接口

    package test.soundsystem;
    
    import javax.inject.Named;
    
    @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);
        }
    }

    3.自动装配类

    package test.soundsystem;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    import test.voice.Book;
    
    @Configuration
    @ComponentScan(basePackageClasses={Book.class,CompactDisc.class})
    public class CDPlayerConfig {
    }

    4.测试类:

    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();
        }
    }

    测试结果:





  • 相关阅读:
    vue中$route和$router的区别
    vscode
    好用的天气插件
    jQuery的slideUp和slideDown函数
    在CSS/JS之后开发工作人员经常会考虑的性能优化。从用户刷新页面,一次js请求下有哪些地方需要缓存
    前端与BI
    XSS和CSRF区别
    兼容性问题
    div跟随鼠标移动
    匀速运动
  • 原文地址:https://www.cnblogs.com/zhengwenqiang/p/6804678.html
Copyright © 2011-2022 走看看