初识Spring Cloud系列——Spring Boot篇01

870 阅读2分钟

这是我参与更文挑战的第1天,活动详情请查看:更文挑战

什么是Spring Boot?

打小,我们学东西,总是先以貌取型,然后把这东西反复记忆,就知道它是啥了;那么Spring Boot长什么样呢?

Spring Boot的特征?

  • Create stand-alone Spring applications

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

  • Provide opinionated 'starter' dependencies to simplify your build configuration

  • Automatically configure Spring and 3rd party libraries whenever possible

  • Provide production-ready features such as metrics, health checks, and externalized configuration

  • Absolutely no code generation and no requirement for XML configuration 简单点说:Spring Boot 使您能轻松地创建独立的、生产级的、基于 Spring 且能直接运行的应用程序。

Spring Boot相关注解

  • Bean声明
    • @Component:用于基础层通用组件
    • @Service:用于业务逻辑层
    • @Controller:用于展现层
    • @Repository:用于数据访问层
  • Bean注入
    • @Autowired:服务依赖注入,用于注入@Component、@Service定义的组件
    • @Resource:注入@Repository定义的组件
  • 配置类
    • @Configuration:声明该类为配置类,可替换XML配置文件,被注解的类内部包含一个或多个@Bean注解方法。
    • @Bean:声明该方法的返回值是bean实例
    • @ComponentScan:对Component进行扫描配置
  • Spring MVC注解
    • @RestController:组合注解,为@Controller、@ResponseBody
    • @RequestMapping:包括访问路径和参数
    • @RequestBody:允许Request的参数在Request Body体中
    • @PathVariable:接收基于路径的参数
    • @ExceptionHandler:全局控制器的异常处理
  • ...

Spring Boot怎样搭建?

  1. 在线创建:start.spring.io/
  2. 开发工具创建 注意点:

image.png artifactId:artifactId一般是项目名或者模块名。
groupId:groupId分为几个字段,例如cn.com.fullstack,前面的com叫【域】,后面的是自己起的域名。

image.png

在创建好的项目中,我们写代码时主要用到了java、resources、test这三个文件,如果要导入新的依赖时,则在pom.xml文件中新增对应的依赖即可,如下

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>