Manually set up maven + springboot project

springboot compared to spring for a more simple, not a lot of xml file, you only need to complete through annotations and properties files.

Summarized reviewed after a good article

Connection  https://blog.csdn.net/u013187139/article/details/68944972

I use development tools is idea.

Introduced by dependent jar package maven.

1. Create a new project

next->finish

After the completion of the new directory structure

pom file

<?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.boottest</groupId>
  <artifactId>myboot</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>myboot</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Will build nodes removed, being less than. Add dependency springboot you need to delete.

<?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.boottest</groupId>
    <artifactId>myboot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>myboot</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <!-- Spring boot 父引用-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <dependencies>
        <!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- Spring boot 核心web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- log-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>

    </dependencies>


</project>

Configuration springboot

1. The new controller, service, serviceimpl, dao the package, and a new controller

Add annotations and main method

@Controller
@EnableAutoConfiguration
public class MytestController {

    @RequestMapping("/")
    @ResponseBody
    String test() {
        return "hello world";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MytestController.class, args);
    }


}

Run the main method

visit website

This page represents a successful start.

2. Add business layer

Injection and call the service method in the controller

Start error

This is because the injection springboot default order is the order of the packet, controller when the service has not been implanted injection.

Solution, add annotations in the controller

@ComponentScan(basePackages = {"com.boottest"})

After running normally.

3. Now this architecture is only one controller, but in general the projects are a number of controller.

Modify controller

Add a startup class in the outer layer. New projects when there is a App.java can be used as a startup class, if not it can create one yourself.

Run the main method to access the web

Thus, a basic springboot set up is completed.

 

Integrated mybatis

Add rely pom file, here I added two oracle and mysql, you can select one according to their own circumstances

   <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.1.0</version>
        </dependency>

And usage of spring, like adding testdao interface and xml files

New resource folder

Set resource file in the root directory

新建mapper文件下和xml文件

xml文件

<?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.boottest.dao.TestDao">

    <select id="selectTest" resultType="java.lang.String">
        SELECT test_name FROM  test WHERE id='1'
    </select>

</mapper>

这时候发现没有配置数据库。所以要添加properties文件来配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml

注意,你在xml文件里写的sql语句一定要根据自己情况修改,意思就是你所连接的数据库要有那张表,那个字段。同时properties文件里的数据库连接信息也要改成你自己的。

下面开始检测效果。

在service中注入dao,并调用方法,在controller中调用service方法,将返回值返回到页面显示

运行App的main方法,访问网页

说明我数据库的值取到了并且成功返回到前端。

mybati集成结束。我这里使用的是和spring一样的xml文件的形式绑定dao接口和sql,也可以通过纯注解的形式省去xml,但是不方便后期维护sql,所以我没有使用那种方式。

 

配置log

springboot支持很多种log,我这里选用的是logback

首先需要添加pom中的依赖。我们一开始已经添加好了,所以现在不用再添加了。

添加日志配置的xml

<configuration>
    <!--控制台输出格式(带颜色)-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are by default assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS, Asia/Shanghai} %highlight(%5p) --- [%-5t] %cyan(%c{36}): %m%n</pattern>

            <!-- 常用的Pattern变量 -->
            <!--
              <pattern>
                  %d{yyyy-MM-dd HH:mm:ss} [%level] - %msg%n
                  Logger: %logger
                  Class: %class
                  File: %file
                  Caller: %caller
                  Line: %line
                  Message: %m
                  Method: %M
                  Relative: %relative
                  Thread: %thread
                  Exception: %ex
                  xException: %xEx
                  nopException: %nopex
                  rException: %rEx
                  Marker: %marker
                  %n
              </pattern>
            -->
        </encoder>
    </appender>


    <!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
    <!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->
    <!-- 2.如果日期没有发生变化,但是当前日志的文件大小超过10MB(以下配置的文件大小)时,对当前日志进行分割 重命名-->
    <appender name="syslog"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
         <!--文件路径 -->
        <File>C:/Users/infodba/Desktop/log/sys.log</File>
        <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
        <!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
            <!-- 文件名:log/sys.2017-12-05.0.log -->
            <fileNamePattern>log/sys.%d.%i.log</fileNamePattern>
            <!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
            <maxHistory>30</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- maxFileSize:这是活动文件的大小,默认值是10MB,也可以自己设置 -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <!-- pattern节点,用来设置日志的输入格式 -->
            <pattern>
                %d %p (%file:%line\)- %m%n
            </pattern>
            <!-- 记录日志的编码 -->
            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
        </encoder>
    </appender>
    <!-- 控制台输出日志级别 -->
    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>
    <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
    <!-- com.appley为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
    <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  -->
    <logger name="com.bootdemo" level="DEBUG">
        <appender-ref ref="syslog"/>
    </logger>
</configuration>

在properties文件中引入此xml

这样log就配置完成了。此配置会让log输出在控制台并且在指定位置生成文件。

我的log配置中有写注释,你可以根据自己的需求修改格式,和路径。

控制台日志

生成的日志文件

 

设置默认欢迎页面

新建一个java类,继承

WebMvcConfigurerAdapter

@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("forward:/index.html");

        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);

        super.addViewControllers(registry);

    }


}

添加static文件夹和html页面(springboot默认是从static路径下找的)

访问8080端口进入首页

这样就可以自定义首页,然后控制后续的跳转。

 

junit测试

新建项目时自动生成的AppTest.java文件,如果没有也可以自己创建。

需要引入的依赖已开始也已经添加了

添加注解

@SpringBootTest(classes = App.class)
@RunWith(SpringRunner.class)
public class AppTest {
    /**
     * Rigorous Test :-)
     */


    @Autowired
    TestService service;

    @Autowired
    TestDao testDao;

    @Test
    public void shouldAnswerWithTrue() {
        //assertTrue(true);
        service.demo();
        testDao.selectTest();

    }
}

 

总结

其实idea可以直接新建springboot的项目结构,感兴趣的可以去搜一下。但是我个人觉得这样一步步手动搭建起来更有助于理解springboot的整体架构。同时可以灵活配置自己喜欢的风格。熟悉了之后在用idea直接生成就没有那么陌生。

 

 

Guess you like

Origin blog.csdn.net/github_39538842/article/details/85044159