在上一節(jié)中我們搭建了一個(gè)簡(jiǎn)單的Spring Boot項(xiàng)目。在這一節(jié)中我們來根據(jù)項(xiàng)目初步了解Spring Boot中常用的注解。
首先在啟動(dòng)類同級(jí)目錄下新建controller目錄,在controller目錄中新建java類:DemoController.java

在DemoController.java中我們利用注解實(shí)現(xiàn)一個(gè)簡(jiǎn)單的接口。
@RestController
public class DemoController {
@GetMapping("/test")
public String test() {
return "test";
}
}
可以看到在這個(gè)類中使用了兩個(gè)注解,@RestController和 @GetMapping。
啟動(dòng)項(xiàng)目,在瀏覽器中輸入:http://localhost:8080/test
可以看到瀏覽器中輸出test字符。
接下來分析代碼。
查看RestController的源碼如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(
annotation = Controller.class
)
String value() default "";
}
從RestController 源碼中可以看到RestController 注解了@Controller和@ResponseBody。因此這個(gè)接口可以返回?cái)?shù)據(jù)。
關(guān)于更多的注解詳解可以點(diǎn)擊這里
查看GetMapping的源碼如下:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
method = {RequestMethod.GET}
)
public @interface GetMapping {
...
從GetMapping 源碼中可以看到注解了RequestMapping而且賦予了get類型。
也就是說@GetMapping的作用等同于@RequestMapping(method = {RequestMethod.GET})而且更加簡(jiǎn)潔。
在以往的spring項(xiàng)目中,單單注解了@Controller或者@RestController加上@RequestMapping還不能真正意義上的說它就是SpringMVC 的一個(gè)控制器類,因?yàn)檫@個(gè)時(shí)候Spring 還不認(rèn)識(shí)它。需要通過在xml中配置掃描包路徑或者在xml中單獨(dú)配置這個(gè)java類,而在Spring Boot中完全免去了這一步。Spring Boot默認(rèn)掃描啟動(dòng)類同級(jí)目錄下的所有文件,所以在這里無需其他的xml配置直接就可以直接訪問接口。
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
在項(xiàng)目的啟動(dòng)類中,發(fā)現(xiàn)idea默認(rèn)為我們加上了一個(gè)注解@SpringBootApplication,查看SpringBootApplication源碼如下:
@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 {
...
我們先關(guān)注SpringBootApplication 上的@ComponentScan,這個(gè)注解就是指引項(xiàng)目啟動(dòng)之后spring掃描包的路徑,如果你不希望spring在項(xiàng)目啟動(dòng)時(shí)掃描全局,那么可以在啟動(dòng)類中使用這個(gè)注解來配置spring的掃描路徑??s小掃描的范圍可以縮短項(xiàng)目啟動(dòng)時(shí)間。
@SpringBootApplication
@ComponentScan(basePackages={"com.example.demo.controller"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
在這一節(jié)中,我們了解到了一些Spring Boot常用的注解以及寫了一個(gè)rest接口。在下一節(jié)我們將詳細(xì)的對(duì)Spring boot的注解進(jìn)行分析Spring Boot從入門到精通-注解詳解
您的關(guān)注是我最大的動(dòng)力