Spring-BootSpringBoot极简教程 · Spring Boot 编程技术

06、vue-admin

2018-04-21  本文已影响95人  spilledyear

源码地址
vue-admin 应用基于 spring-boot2 + mybatis + mysql,专门负责为 vue-monitor 应用提供接口,这样就做到了前后端分离。之后可能会陆续加入其它模块,以微服务的形式运行。本文的主要目的是简单介绍 spring-boot + mybatis + mysql 整合过程,很简单,但是有一些坑,这里进行了总结。

也有想过后台用node,但目前自己对node基本没有过了解。而且,技术发展方向还是比较喜欢偏Java后台的,所以这里用了spring-boot

新建 spring-boot 应用

最简单的办法就是在IDEA中新建项目的时候选择 Spring Initializr ,但是我用这种方法失败了,可能是网络原因吧。于是发现了另一种方法,Spring Initializr,打开这个网站,填好信息,就可以下载一个应用,然后用IDEA打开就好了。打开之后项目结果如下 :

image.png

其实 mysql 、mybatis等一些依赖,在新建的spring-boot应用的时候就可以选择,如图就是我在新建应用时选择的三个依赖

image.png

代码结构如下:

image.png

最终的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>com.hand.sxy</groupId>
    <artifactId>vue-admin</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>vue-admin</name>
    <description>Spring Boot Project For Admin</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>
</project>

application.properties 文件内容

server.port = 8081application.properties 文件内容
spring.datasource.url = jdbc:mysql://10.132.241.120:3306/vue?characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

mybatis.mapper-locations = classpath:**/*.xml

logging.level.com.hand.sxy = DEBUG

启动应用

其实开发模式和之前并没有什么区别,这种默认的规范比较好用:controller->service->mapper。在这个应用中也是一样的,为了测通流程,这里新建了一个表,user 表

CREATE TABLE `user` (
  `USER_ID` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `USERNAME` varchar(200) NOT NULL COMMENT '用户名',
  `PASSWORD` varchar(200) NOT NULL COMMENT '密码',
  `PHONE` varchar(100) DEFAULT NULL COMMENT '电话号码',
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

要测试的很简单,提供一个接口,接口中查询了user表的记录,如果可以查到记录,就说明走通了整个流程。
LoginController.java

package com.hand.sxy.system.controller;

import com.hand.sxy.account.dto.User;
import com.hand.sxy.system.service.ILoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author spilledyear
 * @date 2018/4/21 12:58
 */
@RestController
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private ILoginService loginService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, User user) {
        loginService.login(user);
        logger.info("登录成功");
        return "success";
    }

}

LoginServiceImpl

package com.hand.sxy.system.service.impl;

import com.hand.sxy.account.dto.User;
import com.hand.sxy.account.service.IUserSrvice;
import com.hand.sxy.system.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author spilledyear
 * @date 2018/4/21 13:02
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private IUserSrvice userSrvice;

    @Override
    public boolean login(User user) {
        List<User> userList = userSrvice.query(user);
        return (userList != null && !userList.isEmpty());
    }
}

浏览器上访问结果如下

image.png

后台日志

image.png

至此,整个流程测试完成。

问题

在开发中,其实遇到了几个问题,这里总结一下。

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userMapper in com.hand.sxy.account.service.impl.UserServiceImpl required a bean of type 'com.hand.sxy.account.mapper.UserMapper' that could not be found.


Action:

Consider defining a bean of type 'com.hand.sxy.account.mapper.UserMapper' in your configuration.

提示找不到 UserMapper 这个been。额,我一开始是给 UserMapper 加了个@Service注解,发现还是报一样的错。解决方法有了两种:
1、在 UserMapper文件上添加 @Mapper注解

package com.hand.sxy.account.mapper;

import com.hand.sxy.account.dto.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author spilledyear
 * @date 2018/4/21 13:33
 */
@Mapper
public interface UserMapper {
    /**
     * 查询用户
     *
     * @param user
     * @return
     */
    List<User> query(User user);
}

2、在 VueAdminApplication 文件上添加 @MapperScan 注解

package com.hand.sxy;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 如果不加 MapperScan 这个注解,会提示 xxxMapper 不是一个有效Been
 * @author spilledyear
 */
@SpringBootApplication
@MapperScan("com.hand.sxy.*.mapper")
public class VueAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(VueAdminApplication.class, args);
    }
}
Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

网上很多地方提示加上 useSSL=false 就可以了, 但是如果只是加上这个的话, 会报错如下:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 250 milliseconds ago.  The last packet sent successfully to the server was 242 milliseconds ago.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_101]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_101]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_101]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_101]
    xxx
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.8.0_101]
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949) ~[na:1.8.0_101]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) ~[na:1.8.0_101]
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296) ~[na:1.8.0_101]
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509) ~[na:1.8.0_101]
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) ~[na:1.8.0_101]
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979) ~[na:1.8.0_101]
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914) ~[na:1.8.0_101]
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062) ~[na:1.8.0_101]
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[na:1.8.0_101]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[na:1.8.0_101]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[na:1.8.0_101]
    at com.mysql.jdbc.ExportControlled.transformSocketToSSLSocket(ExportControlled.java:186) ~[mysql-connector-java-5.1.46.jar:5.1.46]
    ... 105 common frames omitted
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
    at com.mysql.jdbc.ExportControlled$X509TrustManagerWrapper.checkServerTrusted(ExportControlled.java:302) ~[mysql-connector-java-5.1.46.jar:5.1.46]
    at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:922) ~[na:1.8.0_101]
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491) ~[na:1.8.0_101]
    ... 113 common frames omitted
Caused by: java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors
    at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:153) ~[na:1.8.0_101]
    at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79) ~[na:1.8.0_101]
    at java.security.cert.CertPathValidator.validate(CertPathValidator.java:292) ~[na:1.8.0_101]
    at com.mysql.jdbc.ExportControlled$X509TrustManagerWrapper.checkServerTrusted(ExportControlled.java:295) ~[mysql-connector-java-5.1.46.jar:5.1.46]
    ... 115 common frames omitted   

解决方法是 在 url 后面加上 autoReconnect=true&useSSL=false

spring.datasource.url = jdbc:mysql://10.132.241.120:3306/vue?characterEncoding=utf8&autoReconnect=true&useSSL=false

源码地址

…or create a new repository on the command line echo "# vue-admin" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/spilledyear/vue-admin.git
git push -u origin master


…or push an existing repository from the command line
git remote add origin https://github.com/spilledyear/vue-admin.git
git push -u origin master
上一篇下一篇

猜你喜欢

热点阅读