spring boot介紹及使用詳解

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員再也不須要定義樣板化的配置。經過這種方式,Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。java

Spring boot的特色mysql

  1. 建立獨立的Spring應用程序
  2. 嵌入的Tomcat,無需部署WAR文件
  3. 簡化Maven配置
  4. 自動配置Spring
  5. 提供生產就緒型功能,如指標,健康檢查和外部配置
  6. 絕對沒有代碼生成和對XML沒有要求配置

Spring boot的優勢nginx

spring boot 能夠支持你快速的開發出 restful 風格的微服務架構web

自動化確實方便,作微服務再合適不過了,單一jar包部署和管理都很是方便。只要系統架構設計合理,大型項目也能用,加上nginx負載均衡,輕鬆實現橫向擴展redis

spring boot 要解決的問題, 精簡配置是一方面, 另一方面是如何方便的讓spring生態圈和其餘工具鏈整合(好比redis, email, elasticsearch)spring

Spring boot的使用sql

一、maven配置文件apache

<?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>org.springboot.sample</groupId>
    <artifactId>spring-boot-sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>spring-boot-sample</name>
    <description>Spring Boot Sample Web Application</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
        <relativePath /> 
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- MYSQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Spring Boot JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

二、application類json

@SpringBootApplication
@ServletComponentScan
public class SpringBootApplication extends SpringBootServletInitializer {
 
    private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(SpringBootSampleApplication.class, args);
    }
}

三、配置類api

@Repository
@Component
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter implements EnvironmentAware{
    private static final Logger logger = LoggerFactory.getLogger(MyWebAppConfigurer.class);
    private RelaxedPropertyResolver propertyResolver;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多個攔截器組成一個攔截器鏈
        // addPathPatterns 用於添加攔截規則
        // excludePathPatterns 用戶排除攔截
        registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/res/**").addResourceLocations("classpath:/res/");
        // 能夠直接使用addResourceLocations 指定磁盤絕對路徑,一樣能夠配置多個位置,注意路徑寫法須要加上file:
        registry.addResourceHandler("/imgs/**").addResourceLocations("file:D:/imgs/");
        super.addResourceHandlers(registry);
    }
}

四、添加filter

@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {
    @Override
    public void destroy() {
        System.out.println("過濾器銷燬");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("執行過濾操做");    
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("過濾器初始化");
    }
}

五、controller

@RestController
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/info")
    public Map<String, String> getInfo(@RequestParam String name) {
        Map<String, String> map = new HashMap<>();
        return map;
    }    
}

六、service

@Service
public class HelloWorldService {
    public String getHelloMessage() {
        return "Hello world";
    }
}

七、全局異常處理

@ControllerAdvice
 public class GlobalExceptionHandler {
     @ExceptionHandler(RuntimeException.class)
     @ResponseBody //在返回自定義相應類的狀況下必須有,這是@ControllerAdvice註解的規定
     public MyExceptionResponse exceptionHandler(RuntimeException e, HttpServletResponse response) {
       
         return resp;
     }
 }
 說明:

@ControllerAdvice是controller的一個輔助類,最經常使用的就是做爲全局異常處理的切面類
@ControllerAdvice能夠指定掃描範圍
@ControllerAdvice約定了幾種可行的返回值,若是是直接返回model類的話,須要使用@ResponseBody進行json轉換
一、返回String,表示跳到某個view
二、返回modelAndView
三、返回model + @ResponseBody

八、添加被其餘配置使用的bean

@Bean
public PageHelper pageHelper(DataSource dataSource) {
    PageHelper pageHelper = new PageHelper();
    return pageHelper;
}

九、添加數據加載類

@Component
public class MyStartupRun implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務啓動執行");
    }
}

該組件在項目啓動時會當即執行
文章最後喜歡的小夥伴能夠關注我下,之後帶來更多精彩內容

相關文章
相關標籤/搜索