springboot 入門一 hello world!,springboothello
微服務架構springboot,目的是用來簡化新Spring應用的初始搭建以及開發過程。簡化的代價,就是約定俗成很多規則,比如預設讀取的設定檔名是application.properties 必需在config目錄下,啟動類的掃描是平級及子目錄。springboot並非是現有問題新的解決方案,而是一種為平台開發帶來新的體驗,簡化繁雜的xml等各種變動不大的配置資訊,約定優於配置。
Boot對Spring應用的開發進行了簡化,提供了模組化方式匯入依賴的能力,強調了開發RESTful Web服務的功能並提供了產生可運行jar的能力,這一切都清晰地表明在開發可部署的微服務方面Boot架構是一個強大的工具。
要實現一個url : http://localhost:8080/index 返回字串:hello world!,
以前的做法:配置web.xml spring-***.xml 再組合tomcat或jetty應用伺服器。
spring boot寫法(maven項目)
一、pom.xml引用包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
二、添加controller
@RestController
public class HomeController {
@RequestMapping("index")
public String index(){
return "hello world!";
}
}
三、添加啟動類
@SpringBootApplication
public class AppBootApplication {
public static void main(String[] args) {
SpringApplication.run(AppBootApplication.class, args);
}
}
四、運行啟動類即可
是不是很簡化,全程沒配置spring相關等xml檔案。spring高版本越來越使用註解來代替xml配置。預設內建spring-boot-starter-tomcat應用,預設連接埠為8080
@RestController是一個封裝註解,集合@Controller+@ResponseBody 標識此類所有路由方法返回string
@SpringBootApplication也是一個封裝註解,@Configuration @EnableAutoConfiguration @ComponentScan
@Configuration 標識類可以使用Spring IoC容器作為bean定義的來源
@EnableAutoConfiguration 能夠自動設定spring的上下文,通常會自動根據你的類路徑和你的bean定義自動設定。
@ComponentScan 會自動掃描指定包下的全部標有@Component的類,並註冊成bean
運行服務有三種方式
1、運行啟動類,直接跑main方法
2、命令列中使用 mvn spring-boot:run
3、可產生單獨執行的jar
在pom.xml添加外掛程式
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
然後打成jar包: mvn package
執行: java -jar spring-boot-1.0.0-SNAPSHOT.jar 即可。