SpringBoot bean 注入的问题

1.SpringBoot Bean 的扫描规则

  • 1.默认从【Application启动类】所在的包位置从上往下扫描
  • 2.如果需要扫描的类不在启动类所在包当前包或者启动类所在包的子包中,那么需要在启动类中配置@ComponentScan注解来添加这些类的包

2.Application启动类

【SpringBoot项目入口类】这个类的位置很关键:启动类如下(Spring自动生成的启动类)
启动类

3.测试类的所在位置的要求

测试类【必须】启动类当前目录或者启动类所在类的子目录(把测试类看作一般类即可),如果想把测试类放到启动类的父级目录,首先要1.把启动类的位置修改到目标目录2.再修改测试类的位置到目标目录

4.举例

  • 1.如果Application类所在的包为:com.test.app,则只会扫描com.test.app包及其所有子包
  • 2.如果被扫描类所在包不在com.test.app及其子包下,则不会被扫描!比如有类在com.test.pc 下
  • 3.如果要扫描到com.test.pc下面的类,那么需要在启动类中配置注解:@ComponentScan(basePackages = {“com.test”}),把需要扫描的包配置进来
  • 4.如果要想把测试类放到 com目录下,首先要把启动类移动到 com目录下,然后再把测试类移动到com目录下

5.总结:一个类要被扫描到需要满足的条件

  • 1.类必须在启动类同一个包下面或者在启动类包子包中 。
  • 2.被扫描的类如果不再启动类所在包及其子包中,那么需要在测试类上配置@ComponentScan注解把需要被扫描的包配置进来。
  • 3.测试类必须在启动类当前目录或者启动类目录的子目录下面

6.例子

项目结构:
这里写图片描述
启动类:

package com.example.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com"})
public class DemoRabbitmqApplication {


    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoRabbitmqApplication.class, args);
    }
}

测试类:

package com.example.rabbitmq;

import com.demo.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by zhangtengda on 2018/5/30.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class CheckTest {

    @Autowired
    private Person person;

    @Test
    public void testPerson() {
        person.say("dada", 5);
    }


}

猜你喜欢

转载自blog.csdn.net/tengdazhang770960436/article/details/80542382
今日推荐