Spring Boot 笔记

最近有几个小项目需要进行相关技术预研,使用了Spring Boot这套框架。
整个过程有一些零散,从头入门的教程网上很多了,就不再重复写了。只是把自己认为有重要的或者有坑的地方记录下来。

1.引用Spring Boot 版本及基础配置

这里使用Spring IO Platform 项目,看介绍是可以减轻包管理版本的难度,直接按照官网加入进来没感觉什么不适。这种方式所有引入的依赖都不需要声明版本。按照这个配置引入Spring Boot 的版本是1.5.9.RELEASE。

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>cn.liveup</groupId>
    <artifactId>platform-pom</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>Brussels-SR6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

其他项目直接将这个项目做parent就可以了。

    <parent>
        <groupId>com.jc.platform</groupId>
        <artifactId>platform</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

2.Spring Boot 启动类的位置

在开发过程发现在Spring Boot 的启动类不能放根下,就是必须得有一个包。要不然启动时会报错。因为Spring Boot 的自动配置,会从启动类所在包向下进行查找配置。类似于@ComponentScan的配置。

3.Spring Boot 启动方式

Spring Boot 正常启动(方式之一)是自己写一个启动类,加上@SpringBootApplication标签。
代码如下:

@SpringBootApplication
public class PlatformApplication {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(PlatformApplication.class);
        application.run(args);
    }
}

pom.xml 配置

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

这种方式就可以使用IDE工具启动这个类的main方法运行或调试了,比较方便,启动整也很快。

4.Spring Boot 项目打成War包放到Tomcat里运行

如果需要放到Tomcat下运行,这种就不行了。
需要再增加一个类继承SpringBootServletInitializer类。

public class ProductStartApplication extends SpringBootServletInitializer {
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(ProductApplication.class);
    }
}

此处的ProductApplication就是上个步骤中使用ProductApplication类,不需要做任何改动。

pom.xml也需要修改,在引入spring-boot-start-web中排除tomcat的相关依赖。并且加入servlet的相关包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 移除嵌入式tomcat插件 -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <!-- <version>3.1.0</version> -->
            <scope>provided</scope>
        </dependency>

这样就可以使用maven的打包命令打包后使用Tomcat运行了。使用IDE调试工具也正常。

5.Spring Boot 项目启动自动运行

1、 CommandLineRunner 接口
Spring Boot 提供了一个接口CommandLineRunner,在Spring Boot 项目启动后自动运行这个接口的实现类,如果有多个实现类,还可以指定先后顺序,并且在实现类中正常使用Spring的功能,比如注入某个类、读取配置文件等。

@Component
@Order(value = 1)
public class PlatformRunner implements CommandLineRunner {

    /**
     * PlatformProperties是Spring boot 配置文件加载类。
     */
    @Autowired
    private PlatformProperties properties;

    @Override
    public void run(String... strings) throws Exception {
        System.out.println(properties.getPlatformName() + "-" + properties.getVersion());
    }
}

2、实现ApplicationListener 接口。

public class RunListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("application start....");
    }
}

ApplictionListener接口的泛型参数有几种不同的事件:
1)ContextRefreshedEvent:当ApplicationContext初始化或者刷新时触发该事件。
2)ContextClosedEvent:当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
3)RequestHandleEvent:在Web应用中,当一个http请求(request)结束触发该事件。
4)ContestStartedEvent:当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
5)ContestStopedEvent:当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。

6.自定义annotation简化配置

目前只是定义了一个annotation,并没有省去太多的配置,但只是一个简单的应用,可以进行一步挖掘项目的使用方法,进行相关的简化,达到统一配置的目的。

/**
 * 将自定义配置文件与启动类简化在一个annotation中,并且可以加入自定义的配置。
 * scanBasePackageClasses,这个配置项目是继承@SpringBootApplication的。
 **/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@PropertySource(value = {"classpath:platform.properties"})
@EnableConfigurationProperties(PlatformProperties.class)
public @interface PlatformApplication {

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};
}

这样在其他引用此项目的其他SpringBoot 项目中就可以使用PlatformApplication这个注解来启动SpringBoot项目了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容