初始化一个项目

你可以直接依赖 AJ 的 Maven(参见《安装》),不过更推荐通过父 pom.xml 依赖方式整合,包含 MySQL 驱动、Tomcat、Spring 等的依赖。 如下是一个 pom.xml 的例子,使用了 aj-common-parent 的 1.7 版本。整个工程的结构跟普通的 Spring Boot 一样,都是main()函数启动。你需要在节点project.mainClass指定项目主类运行入口,也就是main()函数所在的类。

aj-common-parent 当前最新版本: 最新版本


   4.0.0
   
       com.ajaxjs
       aj-common-parent
       1.7
       
   
   aj-iam-server
   1.0
   AJ-IAM Server
   jar

   
       
       com.ajaxjs.iam.server.IamServerApp
   

   
       
       
           org.springframework.data
           spring-data-redis
           2.6.10
       
   

配置

在资源目录中安排 appliaction.yml 文件,内容如下:

server:
    port: 8888 # 端口号
    context-path: /iam  # 项目名,如果不设定,默认是 /
    localFileUpload: # 是否支持本地文件上传
      enable: false

代码结构按照惯常开发的模式即可。必须要有启动类和相关的配置类。

main()函数内的start()必须传入配置类参数;指定@ComponentScan扫面包的范围。

import com.ajaxjs.framework.embeded_tomcat.BaseWebMvcConfigure;
import com.ajaxjs.framework.embeded_tomcat.EmbeddedTomcatStarter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan({"com.ajaxjs.base", "com.ajaxjs.framework.data_service"})
public class BaseApplication extends BaseWebMvcConfigure {
    public static void main(String[] args) {
        EmbeddedTomcatStarter.start(BaseApplication.class); // BaseApplication 为配置类
    }
}

BaseApplication 配置类为:

import com.ajaxjs.data.jdbc_helper.JdbcConn;
import com.ajaxjs.data.jdbc_helper.JdbcWriter;
import com.ajaxjs.iam.resource_server.UserInterceptor;
import com.ajaxjs.util.logger.LogHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;

/**
    * 程序配置
    */
@Configuration
public class BaseConfiguration implements WebMvcConfigurer {
    @Value("${db.url}")
    private String url;

    @Value("${db.user}")
    private String user;

    @Value("${db.psw}")
    private String psw;

    @Bean(value = "dataSource", destroyMethod = "close")
    DataSource getDs() {
        return JdbcConn.setupJdbcPool("com.mysql.cj.jdbc.Driver", url, user, psw);
    }
}

Profiles

在实际使用环境中,我们同一个应用环境可能需要在不同环境运行(开发、测试、生产等),每个环境的参数都有可能不同(连接参数、日志级别等),使用 profiles 可以将不同环境下的参数进行拆分,并指定加载。

IDEA 配置,在 src 目录下创建 profiles 目录,安排如下图的配置文件。

要选择哪个 profile,在 IDEA 里面选 Maven Profile 打勾即可。