Spring Boot从入门到放弃-Application与Controller分离

目录:

第一个程序 hello World

Spring Boot 关闭某些自动配置

Spring Boot 修改banner

Spring Boot 全局配置文件

Spring Boot 从入门到放弃-获取自定义配置

Spring Boot 整合测试

Spring Boot Application与Controller分离

Spring Boot 日志文件

Spring Boot 自定义日志文件

摘要:

      之前我们将Spring Boot启动类Application放在Controller内,这样只能对某一个Controller进行访问。为了统一化管理,我们将Application移出来,形成独立文件。

之前截图:

扫描二维码关注公众号,回复: 8496046 查看本文章

现在将Appliction移出来,因为不能针对Controller 所以为了解决这个问题,我们添加进注解进行Controller进行扫描,和SpringMVC中在xml文件配置包扫描器同样原理。

项目结构截图:

只需要看IndexController.java和MyApplication.java即可。

IndexController.java:

package com.edu.usts.controller;

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

/**
 * create by hgz
 * 2019.12.4 21点13分
 */

@Controller
public class IndexController {

//    返回路径为"/ "即访问地址为:http://localhost:8080/
    @RequestMapping("/")
    @ResponseBody
    public String index(){
        return "hello World!";
    }

}

现有两种扫描办法:

1. 使用  @EnableAutoConfiguration @ComponentScan("com.edu.usts.controller")

@EnableAutoConfiguration 进行Spring Boot自动配置。

@ComponentScan("com.edu.usts.controller")  对controller进行扫描。

package com.edu.usts;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan("com.edu.usts.controller")
public class MyApplication {
    //    启动springboot项目
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

启动截图:

正常可以访问。

2. 使用@SpringBootApplication 进行自动装配扫描。

@SpringBootApplication(scanBasePackages = {"com.edu.usts.controller"}) 自动装配+包扫描,扫描com.edu.usts.controller下的Controller

注:如果Controller在Application类的同层/下一层目录不需要添加scanBasePackages = {"com.edu.usts.controller"},自动进行扫描。如项目结构图,我的Controller在com.edu.usts.controller下,MyApplication在com.edu.usts下所以不需要进行包扫描。

package com.edu.usts;

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

/*@EnableAutoConfiguration
@ComponentScan("com.edu.usts.controller")*/
@SpringBootApplication
public class MyApplication {
    //    启动springboot项目
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

运行截图:

源码gitee地址:

https://gitee.com/jockhome/springboot

发布了41 篇原创文章 · 获赞 108 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_37857921/article/details/103432327