spring boot 备忘

1. 静态资源处理

       spring boot 中默认有对静态资源的处理方式,所以项目中的静态资源,只需要放到 resources 目录下即可,或者在 resources 目录下建立 /statuc、 /public、 /resources、 /META-INF/resources 都行。

       或者扩展 WebMvcConfigurerAdapter 然后自己实现 addReourceHandlers 方法,实现自己定义的资源映射规则。


2. 默认首页

       spring boot 中默认会载入静态资源文件夹根目录的 index.html。也就是说你输入 http://localhost:8080,会跳转到 http://localhost:8080/index.html。

        但若是你的静态资源文件夹中可能有多个不同模块的首页,则可以通过扩展 WebMvcConfigurerAdapter 中的 addViewControllers 来实现不同路径的不同首页加载。

@Configuration
public class IndexPageAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
        registry.addViewController("/en/").setViewName("forward:/en/index.html");
        registry.addViewController("/admin/").setViewName("forward:/admin/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

 

3. 不同环境配置

        实际工作中我们需要对 spring boot 运行时的配置区分为开发环境、测试环境以及生产环境,不同环境的配置使用配置文件的方式比较简单。 spring boot 中默认的配置文件为 application.properties 文件,我们可以将所有环境的通用配置写入该文件,然后新建三个文件 application-dev.properties、application-test.properties、application-prod.proterties 分别对应 开发、测试和生产,各自不同的配置写入各自的文件中。

        在application.properties中 添加 spring.profiles.active=dev 配置默认的环境为开发环境。

        编译打包完成之后, 使用 java -jar XXX.jar --spring.profiles.active=test 来启动测试环境配置的jar包(生产环境类似)。


4. 使用 maven 打包不同环境的 jar 包

      maven 打包编译不同环境的包,还是利用到到了 maven 的 profile,但是与传统方式不同的是,占位符的书写方式是 @name@,如下:

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <spring.profiles.active>test</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

           占位符:

[email protected]@


5. 部署到 linux 服务器

1. 添加 maven-plugin 

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>


2. centos7 使用 systemctl 指令将jar包做成系统服务。首先需要编辑一个 service 文件,放到 /etc/systemd/system/ 中,比如 myapp.service

[Unit]
Description=myapp service
After=syslog.target

[Service]
User=root
Type=simple
ExecStart=/root/app/myapp.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

然后使用   systemctl daemon-reload 刷新服务;

systemctl enable myapp.service 设置开机重启(视情况而定)

systemctl start myapp.service 启动服务










猜你喜欢

转载自blog.csdn.net/zxcvqwer19900720/article/details/73497962