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

    测试结果:





  • 相关阅读:
    php内存管理机制、垃圾回收机制
    Redis 3.2.1集群搭建
    centos开启IPV6配置方法
    /etc/hosts.allow和/etc/hosts.deny详解
    3元购买微信小程序解决方案一个月
    linux下使用ntfs-3g挂载NTFS出错
    腾讯云微信小程序域名变更指南
    nginx开启gzip压缩
    centos 7使用yum安装docker容器
    linux中启动网卡报错:Bringing up interface eth1: Error: Connection activation failed
  • 原文地址:https://www.cnblogs.com/zhengwenqiang/p/6804678.html
Copyright © 2011-2022 走看看