Spring Boot原理以及常用注解

一、什么是SpringBoot?

SpringBoot是一个快速开发框架,快速的将一些常用的第三方依赖整合(原理:通过Maven子父工程的方式),简化XML配置,全部采用注解形式,内置Http服务器(Jetty和Tomcat),最终以java应用程序进行执行。

二、SpringBoot核心原理

1> 基于SpringMVC无配置文件(纯Java)完全注解化+内置tomcat-embed-core实现SpringBoot框架,Main函数启动。

2> SpringBoot核心快速整合第三方框架原理:Maven继承依赖关系。

三、SpringBoot重点

3.1:快速整合第三方依赖:maven子父依赖关系。

springboot 通过引用spring-boot-starter-web依赖,整合SpingMVC框架。只需要引用一个jar包,就可以通过Maven继承的方式引用到Spring-aop,Spring-beans,Spring-core,Spring-web等相关依赖。

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
	<!-- SpringBoot 整合SpringMVC -->
	<!-- 为什么我们映入spring-boot-starter-web 能够帮我整合Spring环境 原理通过Maven子父工程 -->
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

springBoot框架流程:先创建Tomcat容器,然后加载class文件,加载过程中如果发现有java代码编写的SpringMVC初始化,就会创建SpringMVC容器。所有程序执行完毕后,项目就可以访问了。

四、SpringBoot常用注解

  1. @RestController和@RequestMapping注解
  2. @EnableAutoConfiguration注解
  3. @Configuration注解
  4. @SpringBootApplication注解
  5. @ResponseBody
  6. @Component
  7. @AutoWired
  8. @RequestParam
  9. @PathVariable
  10. @ControllerAdvice

1、@RestController和@RequestMapping注解

@RestController注解,它继承自@Controller注解。4.0之前的版本,Spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。

当你实现一个RESTful web services的时候,response将一直通过response body发送。为了简化开发,Spring 4.0提供了一个专门版本的controller。下面我们来看看@RestController实现的定义:

  @Target(value=TYPE)    
  @Retention(value=RUNTIME)    
  @Documented    
  @Controller    
  @ResponseBody    
 public @interface RestController 

注: @RestController 和 @RequestMapping 注解是Spring MVC注解(它们不是Spring Boot的特定部分)

2、@EnableAutoConfiguration注解
第二个类级别的注解是 @EnableAutoConfiguration 。这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。Starter POMs和Auto-Configuration:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。

你可以通过将 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一个 @Configuration 类上来选择自动配置。
注:你只需要添加一个 @EnableAutoConfiguration 注解。我们建议你将它添加到主 @Configuration 类上。

如果发现应用了你不想要的特定自动配置类,你可以使用 @EnableAutoConfiguration 注解的排除属性来禁用它们。

<pre name="code" class="java">import org.springframework.boot.autoconfigure.*;  
     import org.springframework.boot.autoconfigure.jdbc.*;  
     import org.springframework.context.annotation.*;  
     @Configuration  
     @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})  
     public class MyConfiguration {  
     }  

3、@Configuration
Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用 SpringApplication.run() ,我们通常建议你使用 @Configuration 类作为主要源。一般定义 main 方法的类也是主要 @Configuration 的一个很好候选。你不需要将所有的 @Configuration 放进一个单独的类。 @Import 注解可以用来导入其他配置类。另外,你也可以使用 @ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。

如果你绝对需要使用基于XML的配置,我们建议你仍旧从一个 @Configuration 类开始。你可以使用附加的 @ImportResource 注解加载XML配置文件。

@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean

@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)})

4、@SpringBootApplication
很多Spring Boot开发者总是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他们的main类。由于这些注解被如此频繁地一块使用(特别是你遵循以上最佳实践时),Spring Boot提供一个方便的 @SpringBootApplication 选择。
该 @SpringBootApplication 注解等价于以默认属性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。

package com.example.myproject;  
    import org.springframework.boot.SpringApplication;  
    import org.springframework.boot.autoconfigure.SpringBootApplication;  
    @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan  
    public class Application {  
        public static void main(String[] args) {  
            SpringApplication.run(Application.class, args);  
        }  
    }

Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解:

@Component  
    @ConfigurationProperties(prefix="connection")  
    public class ConnectionSettings {  
    @NotNull  
    private InetAddress remoteAddress;  
    // ... getters and setters  
    }

5、@ResponseBody
表示该方法的返回结果直接写入HTTP response body中

一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上
@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如
异步获取json数据,加上@responsebody后,会直接返回json数据。

6、@Component
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解

7、@AutoWired
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构
造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。

8、@RequestParam
用在方法的参数前面:

@RequestParam String a =request.getParameter("abc")

9、@PathVariable
路径变量。

	RequestMapping("user/get/mac/{macAddress}")  
    	public String getByMacAddress(@PathVariable String macAddress){  
     	//can do something;  
    	}  

参数与大括号里的名字一样要相同。
以上注解的示范

/** 
 * 用户进行评论及对评论进行管理的 Controller 类; 
 */  
@Controller  
@RequestMapping("/msgCenter")  
public class MyCommentController extends BaseController {  
    @Autowired  
    CommentService commentService;  
  
    @Autowired  
    OperatorService operatorService;  
  
    /** 
     * 添加活动评论; 
     * 
     * @param applyId 活动 ID; 
     * @param content 评论内容; 
     * @return 
     */  
    @ResponseBody  
    @RequestMapping("/addComment")  
    public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) {  
        ....  
        return result;  
    }  
}

10、@ControllerAdvice
全局处理异常的:
@ControllerAdvice
包含@Component。可以被扫描到。
统一处理异常。
@ExceptionHandler(Exception.class)
用在方法上面表示遇到这个异常就执行以下方法。

/** 
 * 全局异常处理 
 */  
@ControllerAdvice  
class GlobalDefaultExceptionHandler {  
    public static final String DEFAULT_ERROR_VIEW = "error";  
  
    @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class})  
    public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception {  
        ModelAndView mav = new ModelAndView();  
        mav.addObject("error","参数类型错误");  
        mav.addObject("exception", e);  
        mav.addObject("url", RequestUtils.getCompleteRequestUrl(req));  
        mav.addObject("timestamp", new Date());  
        mav.setViewName(DEFAULT_ERROR_VIEW);  
        return mav;  
    }}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值