1.起步依赖
创建Maven工程 springboot_demo(打包方式jar)
在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>
2.引导类
只需要创建一个引导类 .
package cn.itcast.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
简单解释一下:
@SpringBootApplication其实就是以下三个注解的总和
@Configuration: 用于定义一个配置类
@EnableAutoConfiguration :Spring Boot会自动根据你jar包的依赖来自动配置项目。
@ComponentScan: 告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。
我们直接执行这个引导类,会发现控制台出现的这个标识
3. Spring MVC实现Hello World输出
我们现在开始使用spring MVC框架,实现json数据的输出。如果按照我们原来的做法,需要在web.xml中添加一个DispatcherServlet的配置,再添加一个spring的配置文件,配置文件中需要添加如下配置
<!-- 使用组件扫描,不用将controller在spring中配置 -->
<context:component-scan base-package="cn.itcast.demo.controller" />
<!-- 使用注解驱动不用在下边定义映射器和适配置器 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteDateUseDateFormat</value>
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
但是我们用SpringBoot,这一切都省了。我们直接写Controller类
package cn.itcast.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/info")
public String info(){
return "HelloWorld";
}
}
我们运行启动类来运行程序 在浏览器地址栏输入 http://localhost:8080/info 即可看到运行结果
4.修改tomcat启动端口
在src/main/resources下创建application.properties
server.port=8088
重新运行引导类。地址栏输入
http://localhost:8088/info
5.读取配置文件信息
在src/main/resources下的application.properties 增加配置
url=http://www.itcast.cn
我要在类中读取这个配置信息,修改HelloWorldController
@Autowired
private Environment env;
@RequestMapping("/info")
public String info(){
return "HelloWorld~~"+env.getProperty("url");
}
6.热部署
我们在开发中反复修改类、页面等资源,每次修改后都是需要重新启动才生效,这样每次启动都很麻烦,浪费了大量的时间,能不能在我修改代码后不重启就能生效呢?可以,在pom.xml中添加如下配置就可以实现这样的功能,我们称之为热部署。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
赶快试试看吧,是不是很爽。