目录
@RestController注解
1、 @RestController注解表示该类中的所有方法都会返回json格式(当在写微服务的接口的时候会提供很大的帮助)。
2、 @RestController不是SpringBoot提供的而是SpringMVC。(SpingBoot是依赖于SpringMVC注解方式启动)
3、 @RestController与@Controller的区别
如果不用@RestController,而使用@Controller可以吗?
这是可以的,但是需要使用@ResponseBody注解来获取json格式,其实@RestController=@Controller+@ResponseBody。
一、 启动方式一
@EnableAutoConfiguration注解
作用:定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中,说白了就叫扫包(默认在当前类里面)。
spring通常建议把main方法所在的类放到一个根目录的包下,@EnableAutoConfiguration(开启自动配置)注解通常都放到main所在类的上面,在我们新建的SpringBoot的项目里面都有这么一个启动类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@EnableAutoConfiguration会在下面这个典型的目录结构逐层搜索加了注解的类,然后调用这些注解。
二、 启动方式二
@SpringbootApplication注解
@SpringbootApplication的出现是为了解决在src/main/java这个目录下的类有过多注解的问题。但在项目的性能方面存在一定问题。
一个@SpringbootApplication相当于@Configuration
,@EnableAutoConfiguration
和@ComponentScan并具有他们的默认属性值。
三、 启动方式三
@ComponentScan注解
作用:扫包。
需要加上扫包范围(尽量缩小范围,大了会影响整个项目的性能),如果是在当前包里面扫。
如果我要下面这两个包的话。
@ComponentScan(basePackages = {"package com.app01.app01","package com.app01.app01.controler;"})
如果扫包比较多的话,写起来是非常麻烦的。还是建议@EnableAutoConfiguration注解方式。
四、 总结
@SpringBootApplication等于@EnableAutoConfiguration + @ComponentScanto 同级包和当前包。
举个栗子吧~
在App01Application.java里面用@ComponentScan是不能扫到userController.java的。