现在的web项目几乎都会用到spring框架,而要使用spring难免需要配置大量的xml配置文件,而springboot的出现解 决了这一问题,一个项目甚至不用部署到服务器上直接开跑,真像springboot所说:“just run”。
org.spring 2013年新开发的框架springboot , 它让一个单独项目的创建变得更加的简单,让所有依赖spring的程序可以做到“just run”。springboot提供大量第三方libraries让我们可以非常轻松的开始创建一个spring工程,甚至不需要再去配置一些繁琐的xml配置文件
Spring官方网站本身使用Spring框架开发,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置文件以及复杂的Bean依赖关系。随着Spring 3.0的发布,Spring IO团队逐渐开始摆脱XML配置文件,并且在开发过程中大量使用“约定优先配置”(convention over configuration)的思想来摆脱Spring框架中各类繁复纷杂的配置(即时是Java Config)。
Spring Boot正是在这样的一个背景下被抽象出来的开发框架,它本身并不提供Spring框架的核心特性以及扩展功能,只是用于快速、敏捷地开发新一代基于Spring框架的应用程序。也就是说,它并不是用来替代Spring的解决方案,而是和Spring框架紧密结合用于提升Spring开发者体验的工具。同时它集成了大量常用的第三方库配置(例如Jackson, JDBC, Mongo, Redis, Mail等等),Spring Boot应用中这些第三方库几乎可以零配置的开箱即用(out-of-the-box),大部分的Spring Boot应用都只需要非常少量的配置代码,开发者能够更加专注于业务逻辑。
框架特点:
1:创建独立的spring应用。
2:嵌入Tomcat, Jetty Undertow 而且不需要部署他们。
3:提供的“starters”poms来简化Maven配置
4:尽可能自动配置spring应用。
5:提供生产指标,健壮检查和外部化配置
6:绝对没有代码生成和XML配置要求
二:我的构建环境
JDK 7
Maven 3
Servlet3容器
三:开发第一个springboot应用 Hello Word!
创建项目
首先使用Maven创建一个普通Maven应用即可,不必是web的。
配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tianmaying</groupId>
<artifactId>spring-web-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-web-demo</name>
<description>Demo project for Spring WebMvc</description>
<!-- 父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 这里一定要配置上java的版本,如果是1.7版本的可不用配置 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!--如果是通过parent方式继承spring-boot-starter-parent则不用此插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写一个类包含处理HTTP请求的方法以及一个
main()
函数:
package boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Application {
@RequestMapping("/")
public String greeting() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动这个main函数,出现以下以下信息表示启动成功:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.5.RELEASE)
2016-11-14 13:48:06.128 INFO 6492 --- [ main] boot.Application : Starting Application on Zones-LR with PID 6492 (D:\Workspaces2014\springbootdemo\target\classes started by sks in D:\Workspaces2014\springbootdemo)
2016-11-14 13:48:06.165 INFO 6492 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@58b942f7: startup date [Mon Nov 14 13:48:06 CST 2016]; root of context hierarchy
2016-11-14 13:48:06.733 INFO 6492 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-11-14 13:48:07.357 INFO 6492 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$44d92cf0] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-14 13:48:07.377 INFO 6492 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-14 13:48:07.383 INFO 6492 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-14 13:48:07.386 INFO 6492 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-14 13:48:07.846 INFO 6492 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-11-14 13:48:08.036 INFO 6492 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-11-14 13:48:08.037 INFO 6492 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.23
2016-11-14 13:48:08.126 INFO 6492 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-11-14 13:48:08.126 INFO 6492 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1963 ms
2016-11-14 13:48:08.649 INFO 6492 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-11-14 13:48:08.652 INFO 6492 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-11-14 13:48:08.652 INFO 6492 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-11-14 13:48:08.947 INFO 6492 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-11-14 13:48:08.954 INFO 6492 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-11-14 13:48:09.008 INFO 6492 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.10.Final}
2016-11-14 13:48:09.009 INFO 6492 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-11-14 13:48:09.010 INFO 6492 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-11-14 13:48:09.146 INFO 6492 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-11-14 13:48:09.392 INFO 6492 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-11-14 13:48:09.471 INFO 6492 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-11-14 13:48:09.647 INFO 6492 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-11-14 13:48:09.647 INFO 6492 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000102: Fetching database metadata
2016-11-14 13:48:09.648 INFO 6492 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000396: Updating schema
2016-11-14 13:48:09.663 INFO 6492 --- [ main] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000261: Table found: springboot.user
2016-11-14 13:48:09.664 INFO 6492 --- [ main] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000037: Columns: [id, name]
2016-11-14 13:48:09.664 INFO 6492 --- [ main] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000108: Foreign keys: []
2016-11-14 13:48:09.664 INFO 6492 --- [ main] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000126: Indexes: [primary]
2016-11-14 13:48:09.664 INFO 6492 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000232: Schema update complete
2016-11-14 13:48:10.014 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@58b942f7: startup date [Mon Nov 14 13:48:06 CST 2016]; root of context hierarchy
2016-11-14 13:48:10.071 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String boot.Application.greeting()
2016-11-14 13:48:10.072 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getbyname]}" onto public java.lang.String boot.UserController.getByName(java.lang.String)
2016-11-14 13:48:10.072 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/save]}" onto public java.lang.String boot.UserController.save()
2016-11-14 13:48:10.072 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/delete]}" onto public java.lang.String boot.UserController.delete()
2016-11-14 13:48:10.073 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/update]}" onto public java.lang.String boot.UserController.update()
2016-11-14 13:48:10.074 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-11-14 13:48:10.075 INFO 6492 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2016-11-14 13:48:10.098 INFO 6492 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-11-14 13:48:10.099 INFO 6492 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-11-14 13:48:10.138 INFO 6492 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-11-14 13:48:10.280 INFO 6492 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-11-14 13:48:10.347 INFO 6492 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-11-14 13:48:10.348 INFO 6492 --- [ main] boot.Application : Started Application in 4.431 seconds (JVM running for 4.674)
访问 http://127.0.0.1:8080/,出现以下信息:
以上是简单的下实例,下面介绍简单的crud操作
由于上文pom.xml文件中已配置mysql所需的jar,所以直接写类即可
新建一个user实体类:
package boot;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.sun.istack.internal.NotNull;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
private String name;
public User() {
}
public User(long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, precision = 10, scale = 0)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
新建一个UserDao:
package boot;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface UserDao extends CrudRepository<User, Long> {
public User findByName(String name);
/* public User save(User user);
public User update(User user);*/
public void delete(User user);
}
新建UserController:
package boot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@Autowired
public UserDao userDao;
@RequestMapping("/getbyname")
@ResponseBody
public String getByName(String name) {
String userId;
User user = userDao.findByName(name);
if (user != null) {
userId = String.valueOf(user.getId());
return "The user id is: " + userId;
}
return "user " + name + " is not exist.";
}
@RequestMapping("/save")
@ResponseBody
public String save() {
User user = new User();
user.setName("张三");
User user2 = userDao.save(user);
if (user != null) {
return "The user id is: " + user2.getId();
}
return "user id is not exist.";
}
@RequestMapping("/update")
@ResponseBody
public String update() {
User user = new User();
user.setId(1);
user.setName("李四");
User user2 = userDao.save(user);
if (user != null) {
return "The user id is: " + user2.getId();
}
return "user id is not exist.";
}
@RequestMapping("/delete")
@ResponseBody
public String delete() {
User user = new User();
user.setId(2);
userDao.delete(user);
return "执行了删除操作";
}
}
准备一个数据库配置文件application.properties:
spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQL5Dialect
建表sql:
CREATE TABLE `user` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
至此springboot crud开发完毕!
运行Application.java main方法以后访问:http://127.0.0.1:8080/save 等,进行数据库操作。