第二章:SpringBoot基础知识-3. SpringBoot启动注解分析

源码下载:https://u11556602.ctfile.com/fs/11556602-361219278java

                https://download.csdn.net/download/qq_36267875/11089023web

如今为止已经能够发如今整个的springboot程序里面使用了许多的注解,首先把这些注解作一个列表:spring

NO 注解 说明
1 @Controller 进行控制器的配置注解,这个注解所在的类就是控制器类
2 @EnableAutoConfiguration 开启自动配置处理
3 @RequestMapping("/") 表示访问的映射路径,此时的路径为"/",访问地址为http:localhost:8080/
4 @ResponseBody 在Restful架构之中,该注解表示直接将返回的数据以字符串或json的形式得到
5    
6    

能够发如今给定的几个注解之中 @EnableAutoConfiguration为整个springboot的启动注解配置,也就是说这个注解应该随着程序的主类一块儿进行定义。json

而对于控制器程序类,因为在项目之中会有许多的控制器,那么最好将这些类统一保存在一个包中,下面咱们将全部的控制器程序类保存在"cn.mldn.microboot.controller" ,是"cn.mldn.microboot"的子包。springboot

强烈建议(spring官方建议):若是要想进行简单方便的开发,全部的程序类必定要在启动类所在包的子包下。架构

1.【microboot-base 模块】创建一个cn.mldn.microboot.controller.HelloController程序类;app

package cn.mldn.microboot.controller;

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

@Controller
public class HelloController {
   @RequestMapping("/")
   @ResponseBody
   public String home() {
        return "www.mldn.cn";
    }
}

2.【microboot-base 模块】启动程序主类;spa

package cn.mldn.microboot;

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

@EnableAutoConfiguration
@ComponentScan("cn.mldn.microboot") //定义一个扫描路径
public class SampleController {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

3.【microboot-base 模块】以上的作法只是传统程序的开发作法,由于如今为止毕竟是两块程序类,这两个彼此之间的联系,须要有一个链接点,而程序配置的“@ComponentScan” 就是负责这个链接处理,可是springboot考虑到了此类的配置问题,因此提出了一个更简化策略,该策略的核心思想:既然程序主类会在全部开发包的父包里面,那么能不能简化点取得配置呢?为此在实际的开发之中会使用一个特殊的符合注解.net

package cn.mldn.microboot;

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

//@EnableAutoConfiguration
//@ComponentScan("cn.mldn.microboot") //定义一个扫描路径
@SpringBootApplication //启动springboot程序,然后自带子包扫描(等同于上面注释的配置)
public class SampleController {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

理论上"@SpringBootApplication=@EnableAutoConfiguration+@ComponentScan+其余配置"。正是由于它有这样的特色,因此之后使用bean实现配置处理的时候将会很是的容易。code

相关文章
相关标签/搜索