​SpringBoot-31-注解详解-1

SpringBoot-31-注解详解-1

@Controller

@Controller是Spring MVC中创建模型并找到相对应视图(VIEW)的,在SpringBoot开始就有这个注释,我们举例说明

    @GetMapping(value = "test")
    public String test(String msg, Model model){
        //在对test页面渲染通过ModeMap,向页面添加了一个msg,
        // 参数,它的值为参数msg的内容
        model.addAttribute("msg",msg);
        return "test"//值test表示的是模板页面对应的名称
    }

test.html中内容

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<h1>Test</h1>
<div th:text="${msg}" ></div>
</body>
</html>

使用浏览器访问结果为:

​SpringBoot-31-注解详解-1

  • 在对test页面渲染通过ModeMap,向页面添加了一个msg,参数,它的值为welcome my test page
  • return值test表示的是模板页面对应的名称。

结果显示的是html,是SpringMVC 中的View部分

@ResponseBody

@ResponseBody一般会和Controller的方法结合,经过HTTP Request Header中的Accept内容,然后通过HttpMessageConverter转换为指定的格式,写入到Response对象的Body中。

当返回数据不是html页面时候,而是某种数据格式(json、xml)的时候使用,例子如下:

    @GetMapping(value = "test2")
    @ResponseBody
    public String test2(String msg, Model model){
        //在对test页面渲染通过ModeMap,向页面添加了一个msg,
        // 参数,它的值为参数msg的内容
        model.addAttribute("msg",msg);
        return "test"//值test表示的是模板页面对应的名称
    }

加上@ResponseBody注解后,该方法返回的不是试图,而是我们方法要求的String,使用PostMan访问http://localhost:8888/test2?msg=hah,显示结果为:

​SpringBoot-31-注解详解-1

:此时方法中的return test 仅仅表示返回结果为test,而不是模板页面对应的名称。

@RestController

@RestController是为了我们开发RESTful  Web Services,特别是在现在非常流行前后端分离,我们后端只需要返回数据例如返回json或者xml数据,此时“@RestController`就非常有用,只是返回数据对象,例子还是用**@Controller**中的例子不过就是controller的注释变为@RestController:

    @GetMapping(value = "rest/test")
    public String test(String msg, Model model){
        //在对test页面渲染通过ModeMap,向页面添加了一个msg,
        // 参数,它的值为参数msg的内容
        model.addAttribute("msg",msg);
        return "test"//值test表示的是模板页面对应的名称
    }

返回的结果为:

​SpringBoot-31-注解详解-1

:返回结果我们使用**@Controller+@ResponseBody的结果相同,实际上在SpringBoot官方解释中也是这样解释的:@RestController is a stereotype annotation that combines @ResponseBody and @Controller.大致意思是@RestControlle注解相当于@Controller+@ResponseBody**合作一起。

在@RestController注解下返回试图

但是如果我们想在**@RestController注解下返回试图,我们可以使用ModelAndView**,具体例子如下

    @GetMapping(value = "rest/main")
    public ModelAndView main(String msg){
        ModelAndView andView = new ModelAndView();
        andView.addObject("msg",msg);
        andView.setViewName("main");
        return andView;
    }

main.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <h1>Main</h1>
    <div th:text="${msg}" ></div>
</body>
</html>

测试结果如下:

​SpringBoot-31-注解详解-1

@Component

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注,其作用是告知Spring要为这个类创建bean,需要路径扫描来自动侦测以及自动装配到Spring容器中

@Component
public class TestComponent {

    public void component(){
        System.out.println("my test component");
    }
}

查看是否注入容器的bean,我们直接在main方法查看

public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(SpringBootPart31Application.classargs);
        //获取所有bean的名称
        String[] names = applicationContext.getBeanDefinitionNames();
        for(String name:names){
            if(name.startsWith("testComponent")){
                System.out.println(name);
            }
        }

    }

结果为,说明TestComponent类以及创建Bean注入容器:

​SpringBoot-31-注解详解-1

@ComponentScan

就是自动扫描组件,该注解默认会扫描该类所在的包下所有的配置类,由SpringBoot源码可知@SpringBootApplication包含了@ComponentScan,部分源码如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  @Filter(type 
= FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication 
{

 /**
  * Exclude specific auto-configuration classes such that they will never be applied.
  * @return the classes to exclude
  */

 @AliasFor(annotation = EnableAutoConfiguration.class)
 Class<?>[] exclude() default 
{};

那例子说明,如图

​SpringBoot-31-注解详解-1

因为**@SpringBootApplication注解在SpringBootPart31Application类上,因此会自动扫描com.learn.springboot包下需要自动侦测以及自动装配到Spring容器中的bean**。也可以自己指定扫描包

@ComponentScan(basePackages = {"com.learn.springboot2","com.learn.springboot"})

基于@Component扩展的注解

@Service

@Component注解的扩展,被@Service注解的POJO类表示Service层实现,从而见到该注解就想到Service层实现,使用方式和@Component相同,@Service的源码如下

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service 

@Repository

@Component注解的扩展,被@Repository注解的POJO类表示DAO层实现,从而见到该注解就想到DAO层实现,使用方式和@Component相同;


原文始发于微信公众号(springboot葵花宝典):​SpringBoot-31-注解详解-1

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/184320.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!