最近要做一个客户端的活,准备使用轻量级的Spring Boot来完成,记录整个Spring Boot学习过程
-
需要准备的内容
- JDK 1.8 or later
- 一个IDE,我习惯于使用Intellij Idea
- Maven
-
克隆Github上的Demo
$ git clone https://github.com/spring-guides/gs-rest-service.git
-
打开Intellij Idea,并导入Demo工程
并直接使用maven的pom.xml导入
-
创建自己新的工程时,只需将Maven文件Copy过去,并使用Maven导入既可
-
创建一个简单的web应用
可以从Demo里找到文件
src/main/java/hello/HelloController.java
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
该类被标记为@RestController,这意味着Spring MVC可以使用它来处理Web请求。@RequestMapping映射/到index()方法。从浏览器调用或在命令行上使用curl时,该方法返回纯文本。这是因为@RestController组合@Controller和@ResponseBody两个注释会导致Web请求返回数据而不是视图。
src/main/java/hello/Application.java
package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
@SpringBootApplication 是一个便利注释,添加了以下所有内容:
@Configuration 标记该类作为应用程序上下文的bean定义的源。
@EnableAutoConfiguration 告诉Spring Boot开始根据类路径设置,其他bean和各种属性设置添加bean。
通常你会添加@EnableWebMvc一个Spring MVC应用程序,但Spring Boot会在类路径上看到spring-webmvc时自动添加它。这会将应用程序标记为Web应用程序并激活关键行为,例如设置a DispatcherServlet。
@ComponentScan告诉Spring在包中寻找其他组件,配置和服务hello,允许它找到控制器。
该main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。您是否注意到没有一行XML?也没有web.xml文件。此Web应用程序是100%纯Java,您无需处理配置任何管道或基础结构。
还有一个CommandLineRunner标记为a 的方法@Bean,它在启动时运行。它检索由您的应用程序创建或由于Spring Boot自动添加的所有bean。它对它们进行分类并打印出来。
-
Maven 打包
-
执行Jar
java -jar target/gs-spring-boot-0.1.0.jar
-
可以通过
localhost:8080
正常访问