Spring boot 入门实例

写道
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
可以 Maven | Gradle | Ant | Starters构建项目,参考: http://start.spring.io/ 可以选择Maven或Gradle生成Demo,Spring boot微服务架构结合Docker容器运行。
  软件版本运行要求请参考官网:  Spring boot官网
  本实例软件版本:JDK1.7 + Spring boot 1.3.5 + Spring 4.2.6 

  常用的starter以及用处可以列举如下:

  • spring-boot-starter: 这是核心Spring Boot starter,提供了大部分基础功能,其他starter都依赖于它,因此没有必要显式定义它。
  • spring-boot-starter-actuator:主要提供监控、管理和审查应用程序的功能。
  • spring-boot-starter-jdbc:该starter提供对JDBC操作的支持,包括连接数据库、操作数据库,以及管理数据库连接等等。
  • spring-boot-starter-data-jpa:JPA starter提供使用Java Persistence API(例如Hibernate等)的依赖库。
  • spring-boot-starter-data-*:提供对MongoDB、Data-Rest或者Solr的支持。
  • spring-boot-starter-security:提供所有Spring-security的依赖库。
  • spring-boot-starter-test:这个starter包括了spring-test依赖以及其他测试框架,例如JUnit和Mockito等等。
  • spring-boot-starter-web:该starter包括web应用程序的依赖库。
<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>ygnet</groupId>
	<artifactId>boot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Springboot</name>
	<url>http://maven.apache.org</url>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.7</java.version>
	</properties>
	
	<!-- Spring Boot 启动父依赖 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.5.RELEASE</version>
		<relativePath />
	</parent>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.2.6.RELEASE</version>
        </dependency>
        	
		<!-- Spring Boot web依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>	
		<!--dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId><scope>runtime</scope>
		</dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
	</dependencies>
	<build>
	    <pluginManagement>  
	        <plugins>  
	          <plugin>  
	            <groupId>org.eclipse.m2e</groupId>  
	            <artifactId>lifecycle-mapping</artifactId>  
	            <version>1.0.0</version>  
	            <configuration>  
	              <lifecycleMappingMetadata>  
	                <pluginExecutions>  
	                  <pluginExecution>  
	                    <pluginExecutionFilter>  
	                      <groupId>org.apache.maven.plugins</groupId>  
	                      <artifactId>maven-dependency-plugin</artifactId>  
	                      <versionRange>[2.0,)</versionRange>  
	                      <goals>  
	                        <goal>copy-dependencies</goal>  
	                      </goals>  
	                    </pluginExecutionFilter>  
	                    <action>  
	                      <ignore />  
	                    </action>  
	                  </pluginExecution>  
	                </pluginExecutions>  
	              </lifecycleMappingMetadata>  
	            </configuration>  
	          </plugin>  
	        </plugins>  
	    </pluginManagement>
		<plugins>
		    <!-- 打Jar包(META-INF) -->
		    <plugin>
	            <groupId>org.apache.maven.plugins</groupId>  
	            <artifactId>maven-jar-plugin</artifactId>  
	            <configuration>  
	                <archive>  
	                    <manifest>  
	                       <addClasspath>true</addClasspath>  
	                       <classpathPrefix>lib/</classpathPrefix>  
	                       <mainClass>yg.boot.App</mainClass>  
	                    </manifest>  
	                </archive>  
	            </configuration>  
	        </plugin>
	        <!-- 项目资源文件 -->
			<plugin>  
			    <groupId>org.apache.maven.plugins</groupId>  
			    <artifactId>maven-resources-plugin</artifactId>  
			    <version>2.5</version>  
			    <executions>  
			        <execution>  
			            <phase>compile</phase>  
			        </execution>  
			    </executions>  
			    <configuration>  
			        <encoding>${project.build.sourceEncoding}</encoding>  
			    </configuration>  
			</plugin>
			<!-- 是否启动测试 -->
		    <plugin>
		        <groupId>org.apache.maven.plugins</groupId>  
		        <artifactId>maven-surefire-plugin</artifactId>
		        <version>2.17</version> 
		        <configuration>
		          <skipTests>true</skipTests>  
		        </configuration>
		    </plugin>
		    <!-- 复制依赖包到项目lib文件夹下 -->
			<plugin>  
			    <groupId>org.apache.maven.plugins</groupId>  
			    <artifactId>maven-dependency-plugin</artifactId>  
			    <version>2.8</version>  
			    <executions>  
			        <execution>  
			            <phase>package</phase>  
			            <goals>  
			                <goal>copy-dependencies</goal>  
			            </goals>  
			        </execution>  
			    </executions>
			    <configuration>
			    	<outputDirectory>${project.basedir}/lib</outputDirectory>
			        <includeScope>compile</includeScope>  
			    </configuration>  
			</plugin>
			<!-- Spring boot 打包 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
Controller
Spring Boot框架提供的机制便于工程师实现标准的RESTful接口,编写Controller代码,首先我们要在pom文件中添加对应的starter,即spring-boot-starter-web,对应的xml代码示例为:
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。
@RequestMapping("/test")表示该控制器处理所有“/test”的URL请求,具体由那个函数处理,要根据HTTP的方法来区分:GET表示查询、POST表示提交、PUT表示更新、DELETE表示删除。
Restful设计指南请参考: RESTFul
Controller的角色,大家可以看到,我这里将很多业务代码混淆在Controller的代码中。实际上,根据 程序员必知之前端演进史一文所述Controller层应该做的事是: 处理请求的参数 渲染和重定向 选择Model和Service 处理Session和Cookies,我基本上认同这个观点,最多再加上OAuth验证(利用拦截器实现即可)。而真正的业务逻辑应该单独分处一层来处理,即常见的service层;
package yg.boot.action;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/test")
public class AppController {	
	@RequestMapping("/sayhello")
	public String sayHello(){
		return "Hello World!";
	}
}
Spring Boot启动 写道
@SpringBootApplication是这个注解是该应用程序入口的标志,然后有熟悉的main函数,通过SpringApplication.run(xxxApplication.class, args)来运行Spring Boot应用。打开SpringBootApplication注解可以发现,它是由其他几个类组合而成的:@Configuration(等同于spring中的xml配置文件,使用Java文件做配置可以检查类型安全)、@EnableAutoConfiguration(自动配置)、@ComponentScan(组件扫描,大家非常熟悉的,可以自动发现和装配一些Bean)
    pom文件里可以看到,org.postgresql这个库起作用的范围是runtime,也就是说,当应用程序启动时,如果Spring Boot在classpath下检测到org.postgresql的存在,会自动配置postgresql数据库连接
# DataSource settings
spring.datasource.url=jdbc:postgresql://localhost:5432/jcbk
spring.datasource.username=jcbk
spring.datasource.password=123456
spring.datasource.driver-class-name=org.postgresql.Driver

# Tomcat Server settings (ServerProperties)
server.port= 9080
server.address= 127.0.0.1
server.sessionTimeout= 30
server.contextPath= /

# Tomcat specifics
tomcat.accessLogEnabled= false
tomcat.protocolHeader= x-forwarded-proto
tomcat.remoteIpHeader= x-forwarded-for
tomcat.basedir=
tomcat.backgroundProcessorDelay=30 \# secs
package yg.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * Hello world!
 */
@SpringBootApplication
public class App {	
    public static void main(String[] args ){
    	SpringApplication.run(App.class,args);
    }
}
写道
直接运行App后,结果如下图所示。启动后访问http://localhost:9080/test/sayhello, 输出 Hello World!





 
 
项目打包 写道
项目打包使用maven-jar-plugin插件即可,生成boot-0.0.1-SNAPSHOT.jar。spring-boot-maven-plugin插件将boot-0.0.1-SNAPSHOT.jar重命名为boot-0.0.1-SNAPSHOT.jar.original,然后生成新boot-0.0.1-SNAPSHOT.jar包,目录结构为:
+---yg
          boot
+---org
          springframework
              boot
                 loader
+----lib
+----META-INF
+----application.properties
Manifest-Version: 1.0
Implementation-Vendor: Pivotal Software, Inc.
Implementation-Title: Springboot
Implementation-Version: 0.0.1-SNAPSHOT
Implementation-Vendor-Id: ygnet
Built-By: oy
Build-Jdk: 1.7.0_45
Class-Path: lib/spring-test-4.2.6.RELEASE.jar lib/spring-core-4.2.6.RE
 LEASE.jar lib/spring-boot-starter-web-1.3.5.RELEASE.jar lib/spring-bo
 ot-starter-tomcat-1.3.5.RELEASE.jar lib/tomcat-embed-core-8.0.33.jar 
 lib/tomcat-embed-el-8.0.33.jar lib/tomcat-embed-logging-juli-8.0.33.j
 ar lib/tomcat-embed-websocket-8.0.33.jar lib/spring-boot-starter-vali
 dation-1.3.5.RELEASE.jar lib/hibernate-validator-5.2.4.Final.jar lib/
 validation-api-1.1.0.Final.jar lib/jboss-logging-3.3.0.Final.jar lib/
 classmate-1.1.0.jar lib/jackson-databind-2.6.6.jar lib/jackson-annota
 tions-2.6.6.jar lib/jackson-core-2.6.6.jar lib/spring-web-4.2.6.RELEA
 SE.jar lib/spring-aop-4.2.6.RELEASE.jar lib/aopalliance-1.0.jar lib/s
 pring-beans-4.2.6.RELEASE.jar lib/spring-context-4.2.6.RELEASE.jar li
 b/spring-webmvc-4.2.6.RELEASE.jar lib/spring-expression-4.2.6.RELEASE
 .jar lib/spring-boot-starter-1.3.5.RELEASE.jar lib/spring-boot-1.3.5.
 RELEASE.jar lib/spring-boot-autoconfigure-1.3.5.RELEASE.jar lib/sprin
 g-boot-starter-logging-1.3.5.RELEASE.jar lib/logback-classic-1.1.7.ja
 r lib/logback-core-1.1.7.jar lib/slf4j-api-1.7.21.jar lib/jcl-over-sl
 f4j-1.7.21.jar lib/jul-to-slf4j-1.7.21.jar lib/log4j-over-slf4j-1.7.2
 1.jar lib/snakeyaml-1.16.jar lib/spring-boot-starter-jdbc-1.3.5.RELEA
 SE.jar lib/tomcat-jdbc-8.0.33.jar lib/tomcat-juli-8.0.33.jar lib/spri
 ng-jdbc-4.2.6.RELEASE.jar lib/spring-tx-4.2.6.RELEASE.jar lib/postgre
 sql-9.4.1208.jre7.jar lib/spring-boot-starter-actuator-1.3.5.RELEASE.
 jar lib/spring-boot-actuator-1.3.5.RELEASE.jar
Start-Class: yg.boot.App
Created-By: Apache Maven 3.0.4
Spring-Boot-Version: 1.3.5.RELEASE
Main-Class: org.springframework.boot.loader.JarLauncher
Archiver-Version: Plexus Archiver

    Start-Class为Spring boot启动类,Main-Class为main方法入口

    相关源码请下载附件

猜你喜欢

转载自yangyangmyself.iteye.com/blog/2334083