0
点赞
收藏
分享

微信扫一扫

springboot控制类跨层级控制(设置包扫描)

Separes 2022-01-05 阅读 66

我们先来看目录结构

控制类:

package com.DFP;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;


@SpringBootApplication
public class main {
    public static void main(String[] args) {
1.获取我们返回的IOC容器
//        ConfigurableApplicationContext run=
       SpringApplication.run(main.class,args);
2.查看容器的组件
//        String[] names=run.getBeanDefinitionNames();
//        for(String name:names)
//        {
//            System.out.println(name);
//        }

    }
}

我们的主类main在com.DFP包下,默认情况下和主类平级的类或者在这个包下的任何子类、孙类都是被自动扫描的。

com.DFP.controller包小的helloWrold类
package com.DFP.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@ResponseBody
//@Controller
@RestController//等同上2
public class HelloWorld {
    @ResponseBody
    @RequestMapping("/hello")
    public String handlen(){
        return "hellow,new DFP";
    }
}

但是在其他包下例如dfp包

我们新建hello2类

package dfp;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@ResponseBody
//@Controller
@RestController//等同上2
public class hello2 {
    @ResponseBody
    @RequestMapping("/hello2")
    public String handlen(){
        return "new DFP跨层级";
    }
}

我们运行结果测试一下

在同级目录下可以被访问

 不在同级目录下不可以访问

 在主(控制)类的添加注解则可以跨层级扫描

@SpringBootApplication(scanBasePackages ="dfp" )

看看结果

 

举报

相关推荐

0 条评论