SpringBoot点滴(1)

spring boot 注意事项

1.项目启动的主类,放置位置在所有类的外层与controller,dao,service,util,entity同层,SpringBoot会自动扫描@SpringBootApplication所在类同级包。

@SpringBootApplication
public class Main {
      public static  void main(String[] args){
         SpringApplication.run(Main.class, args);
    }
 }

 2.WebMvcConfigurerAdapter中默认配置首页static/index.html

 

3.在通过url直接访问页面时,依赖thymeleaf模板引擎。若使用thymeleaf风格的html不需要配置InternalViewResolver,从SpringMVC转SpringBoot,不习惯这种html,需要在application.yaml中配置中央视图解析器

pom.xml中添加;

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

application.yaml 

 在配置文件中加入ViewController中加入映射,便可访问/Resource/templates下的html文件:

 4.在controller中使用@Controller,报错“template might not exist or might not be accessible by any of the configured Template Resolvers”。thymeleaf在返回view时模板解析失败。但我只是回去返回值,并不是渲染页面,将Controller改为RestController后,数据返回正常。

  @RestController注解相当于@ResponseBody + @Controller合在一起的作用。

  @RestController注解Controller,则Controller中的方法无法返回html页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

   如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

原文地址:https://www.cnblogs.com/CaesarLinsa/p/8682280.html