使用spring boot能夠輕鬆建立獨立的,基於Spring框架的生產級別應用程序。Spring boot應用程序只須要不多的spring配置java
接下來簡單介紹如何利用idea新建一個Spring Boot項目web
pom.xml編輯spring
<!-- 將項目打包成jar --> <packaging>jar</packaging>
依賴項shell
<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>
啓動類查看tomcat
@SpringBootApplication public class SpringbootHelloworldApplication { public static void main(String[] args) { SpringApplication.run(SpringbootHelloworldApplication.class, args); } }
@SpringBootApplication=(默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。app
一、@Configuration:提到@Configuration就要提到他的搭檔@Bean。使用這兩個註解就能夠建立一個簡單的spring配置類,能夠用來替代相應的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>
至關於maven
@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的註解類標識這個類可使用Spring IoC容器做爲bean定義的來源。@Bean註解告訴Spring,一個帶有@Bean的註解方法將返回一個對象,該對象應該被註冊爲在Spring應用程序上下文中的bean。ide
二、@EnableAutoConfiguration:可以自動配置spring的上下文,試圖猜想和配置你想要的bean類,一般會自動根據你的類路徑和你的bean定義自動配置。spring-boot
三、 @ComponentScan:會自動掃描指定包下的所有標有@Component的類,並註冊成bean,固然包括@Component下的子註解@Service,@Repository,@Controller。(注:默認只能掃描當前包及其子包下的Bean)
控制器編輯
新建一個HelloWorldController
@RestController public class HelloWorldController { @RequestMapping("hello") String hello(){ return "hello world"; } }
打包
mvn clean package
啓動
## 後臺運行 nohup java -jar **.jar & ## maven方式運行 mvn spring-boot:run
訪問