spring boot 备忘

来源:互联网 发布:sas sql 编辑:程序博客网 时间:2024/05/17 17:56

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 来实现不同路径的不同首页加载。

@Configurationpublic 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>
           占位符:

spring.profiles.active=@spring.profiles.active@


5. 部署到 linux 服务器

1. 添加 maven-plugin 

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


2. 将 jar 包上传到服务器某个目录下,ln 做个链接到 init.d 里面,就能用 service start | stop 来运行 jar包

    sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp (注意这个指令中第一个路径必须写绝对路径)

     service myapp start
    
    将这个服务做成开机启动 chkconfig --add myapp  






原创粉丝点击