Spring Boot: (三)web開發配置

基礎配置

1、訪問靜態資源

1)進入規則爲 / 時

如果進入SpringMVC的規則爲/時,Spring Boot的默認靜態資源的路徑爲:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
  • 1
  • 2

也就是說,在默認的Spring MVC進入規則下,classpath下的META-INF/resources目錄、resources目錄、static目錄和public目錄中的靜態資料是可以直接通過 “http://xxx.com/靜態資源” 的方式訪問到的。如:


2)進入規則爲*.xxx 或者 不指定靜態文件路徑時

如果進入SpringMVC的規則爲*.xxx時(如:*.html),則上述目錄下的靜態資源將無法直接訪問,需要將靜態資源放置到webapp下的static目錄中即可通過 “http://xxx.com/static/靜態資源” 訪問。此外,默認不配置SpringMVC的規則下也可以如此訪問,也就是說這種訪問靜態資源的方式是通用的。如圖所示:


2、自定義攔截器

增加一個攔截器,需要通過繼承WebMvcConfigurerAdapter然後重寫父類中的方法進行擴展。

@Configuration
public class MySpringMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
                System.out.println("自定義攔截器。。。");
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

            }
        };
        // 添加攔截器並設置攔截規則
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

3、自定義消息轉化器

自定義消息轉化器有兩種實現方式,一種是@Bean方式,另一種是自定義攔截器。

1)@Bean方式

只需要在@Configuration的類中添加消息轉化器的@bean加入到Spring容器,就會被Spring Boot自動加入到容器中。


// spring boot默認就有消息轉化器,其編碼格式爲utf-8
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    return stringHttpMessageConverter;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2)自定義攔截器方式

WebMvcConfigurerAdapter的功能很強大,除了可以配置攔截器外,還可以配置消息轉換器。

@Configuration
public class MySpringMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(stringHttpMessageConverter);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4、讀取外部的配置文件

@Configuration
@PropertySource(value = { "classpath:jdbc.properties", "classpath:base.properties" }, ignoreResourceNotFound = true)
public class 任意類 {

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5、Druid DataSource的配置

Druid提供了一個高效、功能強大、可擴展性好的數據庫連接池,常用於替換DBCP和C3P0。但在Spring Boot上配置比較“噁心”,這裏就簡單的貼出個人參照網上的配置代碼,不必深究。

1)引入依賴


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.11</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2)jdbc.properties

項目中一般會創建一個jdbc.properties文件來記錄數據庫的連接信息。

#MySQL
jdbc.url=jdbc:mysql://127.0.0.1:3306/dbxxx?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
#Druid
jdbc.initialSize=0
jdbc.minIdle=0
jdbc.maxActive=150
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3)配置Druid數據源

建議將配置Druid數據源的操作放在@SpringBootApplication註解的類中。

@SpringBootApplication
@Configuration
@PropertySource(value = {"classpath:jdbc.properties"})
public class MyWebApplication{

    @Value("${jdbc.url}")
    public String jdbcUrl;
    @Value("${jdbc.username}")
    public String jdbcUsername;
    @Value("${jdbc.password}")
    public String jdbcPassword;
    @Value("${jdbc.initialSize}")
    public int jdbcInitialSize;
    @Value("${jdbc.minIdle}")
    public int jdbcMinIdle;
    @Value("${jdbc.maxActive}")
    public int jdbcMaxActive;

    @Bean
    public ServletRegistrationBean druidServletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean duridFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        HashMap<String, String> initParams = new HashMap<>();
        // 設置忽略請求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jdbcUrl);
        druidDataSource.setUsername(jdbcUsername);
        druidDataSource.setPassword(jdbcPassword);
        druidDataSource.setInitialSize(jdbcInitialSize);
        druidDataSource.setMinIdle(jdbcMinIdle);
        druidDataSource.setMaxActive(jdbcMaxActive);
        return druidDataSource;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

之後就可以通過@AutoWried註解得到數據源(druidDataSource)了。

6、數據庫框架集成

1)jpa集成

Jpa在使用上跟Hibernate很像,因爲它們之前的關係非同一般,有興趣可以看看《Hibernate與Jpa的關係,終於弄懂》這篇文章。Spring Boot對jpa的支持也是很好的,配置起來非常簡單。

在pom.xml中引用jpa及數據庫驅動(如:mysql)依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在application.yml文件中配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1/dbgirl
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update  #第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以後加載hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器後,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來後纔會。
    show-sql: true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2)MyBatis集成

Mybatis和Spring Boot的整合有兩種方式:

第一種:使用mybatis官方提供的Spring Boot整合包實現,地址:spring-boot-starter

第二種:使用mybatis-spring整合的方式,也就是我們傳統的方式

這裏推薦並使用第二種方式,因爲可以很方便的控制Mybatis的各種配置。這裏假設你已經配置過數據源了(數據源可以是druid、dbcp、c3p0…)。

首先,需要在pom.xml文件中引用mybatis依賴

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

然後,創建一個Mybatis的配置類:

@Configuration
public class MybatisConfig {

    @Autowired
    DruidDataSource druidDataSource;

    @Bean
    @ConditionalOnMissingBean// 當Spring容器中沒有SqlSessionFactoryBean時才創建
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        // 設置數據源
        sqlSessionFactory.setDataSource(druidDataSource);
        // 設置別名掃描包
        sqlSessionFactory.setTypeAliasesPackage("com.lqr.demo3.bean");
        // 設置Mybatis的配置文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:mybatis-config.xml");
        sqlSessionFactory.setConfigLocation(mybatisConfigXml);
        return sqlSessionFactory;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

最後,創建Mapper接口的掃描類MapperScannerConfig:

@Configuration
@AutoConfigureAfter(MybatisConfig.class)// Mybatis的掃描配置必須在SqlSessionFactory被創建之後
public class MapperScanConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.lqr.demo3.mapper");
        return mapperScannerConfigurer;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

7、設置事務管理

Spring Boot中推薦使用@Transactional註解來申明事務。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

當引入jdbc依賴之後,Spring Boot會自動默認分別注入DataSourceTransactionManager或JpaTransactionManager,所以我們不需要任何額外配置就可以用@Transactional註解進行事務的使用。

@Service
@Transactional
public class GirlService {

    @Transactional
    public void insertGirl() {
        Girl girlA = new Girl();
        girlA.setCupSize("A");
        girlA.setAge(18);
        girlRespository.save(girlA);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

@Transactional不僅可以註解在方法,也可以註解在類上。當註解在類上時,意味着此類所有public方法都會開啓事務。如果類級別和方法級別同時使用了@Transactional註解,則使用在類級別的註解會重載方法級別的註解。

8、開啓jsp支持

Spring boot默認內嵌的tomcat是不支持jsp頁面的,如果項目中使用到了jsp,需要導入如下依賴才能正常訪問。

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

二、Web編碼進階

這部分可能跟Spring Boot的關係並不是很大(或者說,並非Spring Boot特有),但很值得我們在編碼方面作爲參考。

1、Spring MVC中新的註解

1)@RestController

現在的Web項目已經越來越趨向於將後端與前端分別開發了,如果貴公司的項目就是使用json來進行前後端交互,且使用Spring MVC來開發的話,就一定會用到下面這2個註解:

@Controller
@ResponseBody
public class GirlController {
    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

而在Spring MVC4之後,我們可以使用@RestController 註解來開發基於Spring MVC4的REST風格的JSON服務。

通俗的說就是@RestController = @Controller + @ResponseBody。

@Controller和@RestController的區別:

如果只是使用@RestController註解Controller,則Controller中的方法無法返回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內容就是Return 裏的內容。 
例如:本來應該到success.jsp頁面的,則其顯示success.

2)http組合註解

Spring4.3中引進了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping},來幫助簡化常用的HTTP方法的映射,並更好地表達被註解方法的語義。

@GetMapping => 
    @RequestMapping(value = "/xxx",method = RequestMethod.GET)
@PostMapping => 
    @RequestMapping(value = "/xxx",method = RequestMethod.POST)
@PutMapping => 
    @RequestMapping(value = "/xxx",method = RequestMethod.PUT)
@DeleteMapping => 
    @RequestMapping(value = "/xxx",method = RequestMethod.DELETE)
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2、數據校驗

Web開發中,對從前端傳過來的數據做數據校驗已經是家常便飯的事了,但如果校驗的數據很多,那麼,一方面在開發上就需要做很多if判斷,另一方面則是代碼上顯得不再簡潔。其實,使用@Valid + BindingResult就可以優雅地解決這樣的問題。使用示例如下:

1)@Valid + BindingResult

首先,使用一個Java Bean來接收前端提交的數據。在這個Java Bean之前加上@Valid,在這個Java Bean之後加上BindingResult(BindingResult參數必須緊跟在@Valid參數之後。)

/**
 * 添加一個女生
 */
@PostMapping(value = "/girls")
public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return ResultUtils.error(-1, bindingResult.getFieldError().getDefaultMessage());
    }
    return ResultUtils.success(girlRespository.save(girl));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2)設置校驗規則

然後,需要在@Valid註解的Java Bean中,使用各種”規則註解”對其中的屬性進行校驗規則的設定。示例如下:

public class Girl {

    private Integer id;

    @NotBlank(message = "這個字段必傳")
    private String cupSize;

    @Min(value = 18, message = "未成年少女禁止入內")
    private Integer age;

    @NotNull(message = "金額必傳")
    private Double money;

    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

示例中,”規則註解”的message值可以在Controller中通過bindingResult.getFieldError().getDefaultMessage()獲取。

這類用於數據校驗的註解還有很多,有興趣的可以好好研究一下:

註解 類型 說明
@AssertFalse Boolean,boolean 驗證註解的元素值是false
@AssertTrue Boolean,boolean 驗證註解的元素值是true
@NotNull 任意類型 驗證註解的元素值不是null
@Null 任意類型 驗證註解的元素值是null
@Min(value=值) BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存儲的是數字)子類型 驗證註解的元素值大於等於@Min指定的value值
@Max(value=值) 和@Min要求一樣 驗證註解的元素值小於等於@Max指定的value值
@DecimalMin(value=值) 和@Min要求一樣 驗證註解的元素值大於等於@ DecimalMin指定的value值
@DecimalMax(value=值) 和@Min要求一樣 驗證註解的元素值小於等於@ DecimalMax指定的value值
@Digits(integer=整數位數, fraction=小數位數) 和@Min要求一樣 驗證註解的元素值的整數位數和小數位數上限
@Size(min=下限, max=上限) 字符串、Collection、Map、數組等 驗證註解的元素值的在min和max(包含)指定區間之內,如字符長度、集合大小
@Past java.util.Date,java.util.Calendar;Joda Time類庫的日期類型 驗證註解的元素值(日期類型)比當前時間早
@Future 與@Past要求一樣 驗證註解的元素值(日期類型)比當前時間晚
@NotBlank CharSequence子類型 驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的首位空格
@Length(min=下限, max=上限) CharSequence子類型 驗證註解的元素值長度在min和max區間內
@NotEmpty CharSequence子類型、Collection、Map、數組 驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0)
@Range(min=最小值, max=最大值) BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子類型和包裝類型 驗證註解的元素值在最小值和最大值之間
@Email(regexp=正則表達式,flag=標誌的模式) CharSequence子類型(如String) 驗證註解的元素值是Email,也可以通過regexp和flag指定自定義的email格式
@Pattern(regexp=正則表達式,flag=標誌的模式) String,任何CharSequence的子類型 驗證註解的元素值與指定的正則表達式匹配
@Valid 任何非原子類型 指定遞歸驗證關聯的對象;如用戶對象中有個地址對象屬性,如果想在驗證用戶對象時一起驗證地址對象的話,在地址對象上加@Valid註解即可級聯驗證

3、面積切面編程(AOP配置)

AOP是Spring中一大核心,若在SpringBoot中要使用AOP只需兩步:

1)引入AOP的starter依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2)編寫切面類

@Aspect
@Component
public class HttpAspect {
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.lqr.controller.GirlController.*(..))")
    public void log() {
    }

    @Before("log()")
    public void deBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // url
        logger.info("url={}", request.getRequestURL());
        // method
        logger.info("method={}", request.getMethod());
        // ip
        logger.info("ip={}", request.getRemoteAddr());
        // 類方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // 參數
        logger.info("args={}", joinPoint.getArgs());

    }

    @After("log()")
    public void doAfter() {
        logger.info("doAfter...");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        if (object != null)
            logger.info("response={}", object.toString());
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

4、統一異常處理(配置通知Advice)

1)自定義異常

這裏之所以繼承RuntimeException,是爲了方便事務回滾。而自定義異常的好處在於:一方面可以使代碼語義化,另一方面使得我們編碼更加方便。

public class GirlException extends RuntimeException {
    private Integer code;

    public GirlException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

2)配置全局異常捕獲器

使用全局異常捕獲器,一方面可以捕獲到整個項目中的Exception及其子類(包含RuntimeException等),另一方面可以對異常進行統一處理並返回統一的數據格式,爲前端提供友好的數據交互。

@ControllerAdvice
public class ExceptionHandle {

    private final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof GirlException) {
            GirlException girlException = (GirlException) e;
            return ResultUtils.error(girlException.getCode(), girlException.getMessage());
        } else {
            logger.error("【系統異常】{}", e);
            return ResultUtils.error(-1, "未知錯誤");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

三、開發與生產

1、熱部署

Web開發中,沒有熱部署怎麼能行呢?所以,下面就介紹下Spring Boot的熱部署配置。

1)在pom.xml中配置熱部署需要的依賴與插件

<dependencies>
    ...
    <!--spring boot 熱部署-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
<build>
    <plugins>
        <!--spring boot 熱部署-->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
    ...
</build>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

2)開啓自動編譯

打開Idea的Settings界面,找到”Build,Execution,Depolyment”,在Compiler中將”Build project automatically”打鉤。

3)修改pom.xml的維護(Maintenance)登記項

使用快捷鍵 “ctrl+shift+alt+/” 打開pom.xml的維護(Maintenance)菜單,找到登記(registry)項,單擊打開。

4)允許應用程序運行時自動編譯

在登記(registry)中找到”compiler.automake.allow.when.app.running”這一項打鉤,關閉。最後重啓項目即可!!!

2、發佈到獨立的tomcat中運行

儘管Spring Boot項目會內置一個tomcat,僅只需通過一個簡單的指令便可啓動項目,但在生產環境下,我們還是習慣將項目發佈到第三外的servlet容器中,下面將介紹如果將一個Spring Boot項目團部署到第三方tomcat中運行。

1)修改工程的打包方式爲war

2)將spring-boot-starter-tomcat的範圍設置爲provided

spring-boot-starter-tomcat是Spring Boot默認就會配置的,即上面說到的內嵌tomcat,將其設置爲provided是在打包時會將該包(依賴)排除,因爲要放到獨立的tomcat中運行,Spring Boot內嵌的Tomcat是不需要用到的。

<!--spring boot tomcat(默認可以不用配置,但當需要把當前web應用佈置到外部servlet容器時就需要配置,並將scope配置爲provided)-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3)修改代碼,設置啓動配置

需要繼承SpringBootServletInitializer,並重寫configure()方法,將Spring Boot的入口類設置進去。

// 若要部署到外部servlet容器,需要繼承SpringBootServletInitializer並重寫configure()
@SpringBootApplication
@Configuration
public class MyWebApplication extends SpringBootServletInitializer
{

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // 設置啓動類,用於獨立tomcat運行的入口
        return builder.sources(MyWebApplication.class);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4)打war包並部署到tomcat

發佈了71 篇原創文章 · 獲贊 14 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章