Springboot创建hello world项目
(1) 创建maven项目
(2) 配置pom.xml文件,写入以下代码:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
(3) 创建spring boot主程序
@SpringBootApplication
public class ClassName(){
public static void main(String[] args){
SpringBootApplication.run(ClassName.class);
}
}
(4) 创建web相关的controller,Service类
@Controller
public class ClassName(){
@ResponseBody
@RequestMapping(“/hello”)
public String hello(){
return “hello world”;
}
}
入门简单探究
(1) pom.xml解析
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
spring-boot-starter-parent:导入了Spring boot所有starter的父项目。spring-boot-starter-parent依赖了spring-boot-dependencies这个父项目,而spring-boot-dependencies里有个属性,属性里定义了各个依赖的版本。因此,spring-boot-dependencies他是真正管理spring boot应用里所有依赖版本的,既spring boot的版本仲裁中心,以后我们导入依赖默认是不需要写版本(没在dependencies里的依赖要写)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
spring-boot-starter-web:spring-boot-starter 是spring boot场景启动器。spring-boot-starter-web里有spring-boot-starter,spring-boot-starter-tomcat,spring-web,spring-webmvc等依赖,这些依赖正是web所需要的。spring-boot-starter-web帮我们导入web模块正常运行所需要的组件。Spring boot将所有功能场景抽取出来,做成一个个starters(启动器),只需要导入这些starters,相关场景的依赖也就导入进去,要什么功能就导什么场景。
(2) spring boot主程序
@SpringBootApplication
public class ClassName(){
public static void main(String[] args){
SpringBootApplication.run(ClassName.class);
}
}
@SpringBootApplication:标注了这个注解的类是springboot的主配置类,spring boot应该运行这个类的main方法启动spring boot应用。这个注解里又有以下注解:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
@ SpringBootConfiguration:表示这是一个spring boot的配置类。这个注解底层有个@Configuration注解,@Configuration标在配置类上,让spring boot知道这是一个配置类。
@EnableAutoConfiguration:开启自动配置功能。
这个注解底层有一个@AutoConfigurationPackage注解,作用是自动配置包。而@AutoConfigurationPackage底层又有一个@Import(AutoConfigurationPackage.Registrar.class)注解,这是spring的底层注解,作用是给容器导入组件,组件由AutoConfigurationPackage.Registrar.class决定。
既@AutoConfigurationPackage是将主配置类(springboot主程序)的所在包及子包下所有的组件扫描到spring容器中。
@EnableAutoConfiguration下还有一个注解@Import(EnableAutoConfigurationImportSelector.class),作用是导入哪些组件的选择器。将所有需要导入的组件以全类名方式返回,添加到容器中,这些组件是自动配置类,就是给容器导入这个场景所需组件,并配置好。