Skip to content

Instantly share code, notes, and snippets.

@congjf
Last active October 16, 2016 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save congjf/4453467a817a754ffbe6d73085a6141f to your computer and use it in GitHub Desktop.
Save congjf/4453467a817a754ffbe6d73085a6141f to your computer and use it in GitHub Desktop.
Spring Boot
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
// BASE
apply plugin: 'java'
// apply plugin: 'war'
apply plugin: 'spring-boot'
// IDE
apply plugin: 'eclipse'
apply plugin: 'idea'
jar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
// tag::jetty[]
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
// end::jetty[]
// tag::actuator[]
compile("org.springframework.boot:spring-boot-starter-actuator")
// end::actuator[]
testCompile("junit:junit")
}
// war {
// from 'src/rootContent' // adds a file-set to the root of the archive
// webInf { from 'src/additionalWebInf' } // adds a file-set to the WEB-INF dir.
// classpath fileTree('additionalLibs') // adds a file-set to the WEB-INF/lib dir.
// classpath configurations.moreLibs // adds a configuration to the WEB-INF/lib dir.
// webXml = file('src/someWeb.xml') // copies a file to WEB-INF/web.xml
// }

Steps

  • Create a build.gradle file, like build.gradle
  • Open IDEA, and import the build.gradle created before

Gradle

The Spring Boot gradle plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.
  • It searches for the public static void main() method to flag as a runnable class.
  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.

Annotation

  • @RestController meaning it’s ready for use by Spring MVC to handle web requests. Combines @Controller and @ResponseBody, two annotations that results in web requests returning data rather than a view.

  • @RequestMapping maps URL Path to method.

  • @SpringBootApplication is a convenience annotation that adds all of the following:

    • @Configuration tags the class as a source of bean definitions for the application context.
    • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
    • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
    • @ComponentScan tells Spring to look for other components, configurations, and services in the the hello package, allowing it to find the HelloController.

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method.

默认情况下,Spring Boot将使用classpath目录或ServletContext根目录下的/static(或 /public/resources/META-INF/resources)来作为静态资源目录。Spring Boot使用来自Spring MVC的ResourceHttpRequestHandler,所以你可以通过添加你自己的WebMvcConfigurerAdapter和覆盖addResourceHandlers方法来改变静态资源目录。

In a stand-alone web application the default servlet from the container is also enabled, and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. Most of the time this will not happen (unless you modify the default MVC configuration) because Spring will always be able to handle requests through the DispatcherServlet.

You can customize the static resource locations using spring.resources.staticLocations (replacing the default values with a list of directory locations). If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html in any of your locations on startup, it will be the home page of the application.

In addition to the ‘standard’ static resource locations above, a special case is made for Webjars content. Any resources with a path in /webjars/** will be served from jar files if they are packaged in the Webjars format.

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar. 如果你的应用将被打包成一个jar包,那么不要使用src/main/webapp directory目录。这个目录是一个仅仅工作在war包内的通用标准,在你生成jar包的时候,这个目录将被忽略。

Spring Boot also supports advanced resource handling features provided by Spring MVC, allowing use cases such as cache busting static resources or using version agnostic URLs for Webjars.

To use version agnostic URLs for Webjars, simply add the webjars-locator dependency. Then declare your Webjar, taking jQuery for example, as "/webjars/jquery/dist/jquery.min.js" which results in "/webjars/jquery/x.y.z/dist/jquery.min.js" where x.y.z is the Webjar version.

If you are using JBoss, you’ll need to declare the webjars-locator-jboss-vfs dependency instead of the webjars-locator; otherwise all Webjars resolve as a 404.

To use cache bursting, the following configuration will configure a cache busting solution for all static resources, effectively adding a content hash in URLs, such as <link href="/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css"/>:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

Links to resources are rewritten at runtime in template, thanks to a ResourceUrlEncodingFilter, auto-configured for Thymeleaf, Velocity and FreeMarker. You should manually declare this filter when using JSPs. Other template engines aren’t automatically supported right now, but can be with custom template macros/helpers and the use of the ResourceUrlProvider.

When loading resources dynamically with, for example, a JavaScript module loader, renaming files is not an option. That’s why other strategies are also supported and can be combined. A "fixed" strategy will add a static version string in the URL, without changing the file name:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12

With this configuration, JavaScript modules located under "/js/lib/" will use a fixed versioning strategy "/v12/js/lib/mymodule.js" while other resources will still use the content one .

See ResourceProperties for more of the supported options.

This feature has been thoroughly described in a dedicated blog post and in Spring Framework’s reference documentation.

package hello;
/**
* Created by CongJF on 2016/10/6.
*/
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
package hello;
/**
* Created by CongJF on 2016/10/6.
*/
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
@RequestMapping("/user")
public String user() {
return "User Page!";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment