簡介
使用spring boot可以輕松創(chuàng)建獨(dú)立的,基于Spring框架的生產(chǎn)級別應(yīng)用程序。Spring boot應(yīng)用程序只需要很少的spring配置
特點(diǎn)
- 創(chuàng)建獨(dú)立的Spring應(yīng)用程序
- 直接嵌入tomcat
- 提供starter依賴項(xiàng),簡化構(gòu)建配置
- 盡可能自動(dòng)配置Spring和三方庫
- 提供生產(chǎn)就緒的功能,例如指標(biāo),運(yùn)行狀況檢查和外部配置
- 完全沒有代碼生成,也不需要XML配置
啟程
接下來簡單介紹如何利用idea新建一個(gè)Spring Boot項(xiàng)目
-
新建項(xiàng)目
創(chuàng)建項(xiàng)目 輸入項(xiàng)目名和包名

-
pom.xml編輯
<!-- 將項(xiàng)目打包成jar --> <packaging>jar</packaging> 依賴項(xiàng)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-
啟動(dòng)類查看
@SpringBootApplication public class SpringbootHelloworldApplication { public static void main(String[] args) { SpringApplication.run(SpringbootHelloworldApplication.class, args); } }@SpringBootApplication=(默認(rèn)屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
1、@Configuration:提到@Configuration就要提到他的搭檔@Bean。使用這兩個(gè)注解就可以創(chuàng)建一個(gè)簡單的spring配置類,可以用來替代相應(yīng)的xml配置文件。
<beans> <bean id = "car" class="com.test.Car"> <property name="wheel" ref = "wheel"></property> </bean> <bean id = "wheel" class="com.test.Wheel"></bean> </beans>相當(dāng)于
@Configuration public class Conf { @Bean public Car car() { Car car = new Car(); car.setWheel(wheel()); return car; } @Bean public Wheel wheel() { return new Wheel(); } }@Configuration的注解類標(biāo)識這個(gè)類可以使用Spring IoC容器作為bean定義的來源。@Bean注解告訴Spring,一個(gè)帶有@Bean的注解方法將返回一個(gè)對象,該對象應(yīng)該被注冊為在Spring應(yīng)用程序上下文中的bean。
2、@EnableAutoConfiguration:能夠自動(dòng)配置spring的上下文,試圖猜測和配置你想要的bean類,通常會自動(dòng)根據(jù)你的類路徑和你的bean定義自動(dòng)配置。
3、 @ComponentScan:會自動(dòng)掃描指定包下的全部標(biāo)有@Component的類,并注冊成bean,當(dāng)然包括@Component下的子注解@Service,@Repository,@Controller。(注:默認(rèn)只能掃描當(dāng)前包及其子包下的Bean)
-
控制器編輯
新建一個(gè)HelloWorldController
@RestController public class HelloWorldController { @RequestMapping("hello") String hello(){ return "hello world"; } }
-
打包
mvn clean package -
啟動(dòng)
## 后臺運(yùn)行 nohup java -jar **.jar & ## maven方式運(yùn)行 mvn spring-boot:run 訪問
