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

    测试结果:





  • 相关阅读:
    方差、协方差、相关系数的理解
    yii2原生sql
    Oracle中日期作为条件的查询
    IDEA 中tomcat图片储存和访问虚拟路径(图片和程序分家)
    nginx配置静态资源:配置绝对路径
    一般spring配置上下文
    spring boot 集成 redis lettuce(jedis)
    windows下面同时部署多个tomcat的方法
    oracel: 通过特殊表序列来实现oracle自增id (mybatis实现自增id)
    使用fastjson 进行jsonObject转实体类对象
  • 原文地址:https://www.cnblogs.com/zhengwenqiang/p/6804678.html
Copyright © 2011-2022 走看看