Spring Boot 工程搭建记录

因为最近在做Spring Boot 的工程改造,正好积累了一点工程经验,这里记录一下。


首先说一下改造过程感受。

Spring Boot,因为有parent pom 的支持(这轮子够大),默认已经整合了很多功能。按照约定大于配置的原则,尽可能的减少配置,通过注解和默认约定,给使用者带来了更多的方便。所以在改造的过程中,看到xml就别扭,必须想办法给干掉。

在这几天接触Spring Boot 和Spring Cloud的过程中。对Boot的使用也有了些认识。

那么今天来从零搭建一下这个Spring Boot 工程。和改造MVC工程比起来,简直是太爽了。


一、创建pom工程

首先创建一个pom工程。

创建父pom

这里一路next即可。

然后分层创建module。操作相同,这里以controller层为例。

创建子module

接下来依然是一路next。创建模块结束。相同操作,创建其他模块,这里根据各自的工程接口自行定义。

module 结构

工程整体结构创建就这样结束了。简单易操作。

二、文件配置

Spring Boot 的约定大于配置,还有一个优点就是配置大于代码。所以必要的配置也是必不可少的。

这里主要配置Boot框架使用到的依赖,目前配置有:Spring Boot,Durid,Mybatis。所以需要对这些进行相应的配置。

在资源目录创建application.yml文件(这就是约定),添加如下配置:

server:
  port: 8990

#datasource
spring:
  datasource:
	#durid 数据源
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/zhenaiapi?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: 用户名
    password: 密码
    driver-class-name: com.mysql.jdbc.Driver
    #这里需要注意的就是这里可以配置dbcp2和tomcat连接配置,我配置的是dbcp2
    dbcp2:
      initial-size: 5
      min-idle: 5
      max-total: 20
      max-wait-millis: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 3000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: false
      test-on-return: false
      pool-prepared-statements: true
  thymeleaf:
    cache: false
#一定要配置好这里的mapper路径,否则导致不能搜索到
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml

以上这些基本是一些常规配置,如果需要特殊配置,可以查看spring-configuration说明。

三、添加pom依赖

工程之所以能使用Spring Boot 特性,也就靠这些了。

 <dependencies>
        <!-- spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!-- thmleaf模板依赖. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

    </dependencies>

四、添加druid配置

这里需要配置一下,主要是为了配置数据库参数和Durid监控。废话少说,直接撸代码。

@Configuration
public class DruidConfiguration {

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

    @Bean
    public ServletRegistrationBean druidServlet() {
        logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("loginUsername", "admin");// 用户名
        initParameters.put("loginPassword", "admin");// 密码
        initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
        initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问)
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

        @Bean
        public FilterRegistrationBean filterRegistrationBean() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
            filterRegistrationBean.setFilter(new WebStatFilter());

            // 添加过滤规则
            filterRegistrationBean.addUrlPatterns("/*");

            // 添加不需要忽略的格式信息.
            filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
            return filterRegistrationBean;
        }

        @Bean
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource druidDataSource() {
            return new DruidDataSource();
        }

}

通过这个配置,服务启动之后,可以查看druid的监控情况。

访问地址:http://127.0.0.1:8990/druid/index.html
创建子module

五、最后一步,业务代码

基本的配置已经结束。接下来就是常规操作,创建controller,service,mapper,dao层,开始调用代码。

建表

这里使用本地mysql,通过

Controller

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping(value = "getUsersById",method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    DataResult<UserVo> getUsersById(@RequestParam("userId") Long userId){

        DataResult<UserVo> dataResult = new DataResult<>();
        dataResult.setData(userService.getUserById(userId));
        return dataResult;
    }

}

Service

@Service
@Slf4j
public class UserService {

    Logger logger = LoggerFactory.getLogger(UserService.class);

    @Resource
    UserMapper userMapper;

    public UserVo getUserById(Long userId) {
        logger.info("userId is {}",userId);
        User user = userMapper.selectByPrimaryKey(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return userVo;

    }
}

Mapper

@Mapper
public interface UserMapper {

    User selectByPrimaryKey(@Param("userId") Long userId);

}

mapper.xml

这里使用本地的mysql数据库,创建一个user表,测试使用。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.gitlearn.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.gitlearn.dao.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <id column="user_code" property="userCode" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
    id, user_code, name, age
  </sql>

    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
        select
        <include refid="Base_Column_List" />
        from user
        where id = #{userId,jdbcType=INTEGER}
    </select>
</mapper>

六、验证

一切准备就绪,如果顺利,启动工程,我们将看到下面一段代码。

Started ApiStartApplication in 9.27 seconds (JVM running for 10.686)

接下来就是用PostMan测试接口:http://localhost:9653/api/user/getUsersById?userId=我需要一个int来替换

返回结果:

{
    "code": 200,
    "message": "SUCESS",
    "data": {
        "id": 我就是你要查的那个userId,
        "userCode": 1,
        "name": "sring boot",
        "age": 5
    }
}

七、总结

工程从零开始,其实也是一种幸福,本篇大致记录了Spring Boot工程初步搭建过程,然后顺手把数据库加上。要想能够使用,还有很多工作要做。

还是那句话,代码就分两种,自己的和别人的。现在是理解并使用别人代码的第一步,理解是使用的基础。刚迈出这一步,就感觉脚下有点软,前面路很长。

我得跑一跑…

喜欢我的文章可以关注我的公众号:蓁爱学习
蓁爱学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值