SpringBoot学习笔记-基础项目搭建

       因为工作需要,最近研究springBoot框架,从零开始什么都不懂,虽然只是基础的项目搭建,但是还是遇到了不少的坑,特此记录下。

        首先,现在开发工具上安装一个spring的插件(懒人专用),这样可以直接生成springBoot项目,不用一个文件一个文件的重新构建。我的开发工具是Eclipse, 步骤 :hellp》Eclipse Marketplace 》popular


然后找见spring Tool是 点击installed然后等一会,等安装结束后进入 window》preferences查看是否有spring的插件,如图:


看到spring就说明插件安装完成,可以进入下一步,构建项目

右键new一个新项目,不过我们选择other然后输入spring可以发现可以直接生成springBoot项目


选中springBoot 下的spring starter project 点击下一步会出现下图


说一下比较重要的部分:

    Name是项目名称

    packging是打包方式:jar/war

    java version是java版本

    package 是构建后的项目路径

都配置好后点击下一步:


springBoot的强大这时候就体现出来了,他将大部分我们可能用到的东西都集成进来,可以直接使用,只需要勾选你所需要的东西就行,因为只是一个简单额demo,所以只勾选几个可能用到的

然后点击finish生成项目,生成的目录结构如下


SpringBootDemo1Application是项目入口,开发启动时需要直接main方法启动就行

application.properties是springboot的配置文件,大部分配置都在里面,后缀可以改成.yml,需要注意的是,不同后缀的配置文件写法是不一定的

application.properties

spring.application.name=compute-service
server.port=80
server.tomcat.uri-encoding=GBK
application.yml
spring: 
  datasource:
    url: jdbc:mysql:数据库url
    password: 数据库密码
    username: 数据库用户名
    driver-class-name: com.mysql.cj.jdbc.Driver
  http:
    encoding:
      charset: UTF-8
      enabled: true
mybatis: 
  config-location: classpath:mybatis-config.xml
server:
  port: 8080  
  sessionTimeout: 30
  contextPath: /StringBoot
然后在同级目录下添加一个mybatis-config.xml文件,文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true" />
		<setting name="lazyLoadingEnabled" value="false" />
		<setting name="multipleResultSetsEnabled" value="true" />
		<setting name="useColumnLabel" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
		<setting name="defaultStatementTimeout" value="25000" />
	</settings>
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<property name="dialect" value="mysql" />
			<property name="offsetAsPageNum" value="true" />
			<property name="rowBoundsWithCount" value="false" />
			<property name="pageSizeZero" value="false" />
			<property name="reasonable" value="true" />
			<property name="supportMethodsArguments" value="false" />
			<property name="returnPageInfo" value="none" />
		</plugin>
	</plugins>
</configuration>
然后修改pom文件,添加一些依赖,修改后为:

<?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.example</groupId>
    <artifactId>springBootDemo-1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springBootDemo-1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <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>
    </dependencies>

    <build>
        <plugins>
                 <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                
                <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <classesDirectory>target/classes/</classesDirectory>
                    <archive>
                        <manifest>
                            <mainClass>com.example.demo.SpringBootDemoApplication</mainClass>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <type>jar</type>
                            <includeTypes>jar</includeTypes>
                            <outputDirectory>
                                ${project.build.directory}/lib
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                        <manifestEntries>
                            <Premain-Class> . </Premain-Class>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
          </plugins>        
    </build>
</project>
然后选中项目,右键:maven》 update maven project执行结束后,右键,run》mavenclean然后在run》maven install 如果项目打包成功则可以继续执行,如果打包失败则说明配置有问题请检查,springBoot项目中自带了test测试用例,所以需要引入junit的jar,如果不需要,也可以直接删除测试用例,测试用例地址在src\test下

然后进入到 SpringBootDemo1Application中  main方法启动,

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

2017-11-13 15:22:31.772  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : Starting SpringBootDemo1Application on AGOE2345-311800 with PID 2384 (D:\workspaceTest\springBootDemo-1\target\classes started by Administrator in D:\workspaceTest\springBootDemo-1)
2017-11-13 15:22:31.774  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : No active profile set, falling back to default profiles: default
2017-11-13 15:22:31.816  INFO 2384 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6ac13091: startup date [Mon Nov 13 15:22:31 CST 2017]; root of context hierarchy
2017-11-13 15:22:32.343  WARN 2384 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.example.demo]' package. Please check your configuration.
2017-11-13 15:22:33.025  INFO 2384 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-13 15:22:33.039  INFO 2384 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-13 15:22:33.041  INFO 2384 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-13 15:22:33.128  INFO 2384 --- [ost-startStop-1] o.a.c.c.C.[.[localhost].[/StringBoot]    : Initializing Spring embedded WebApplicationContext
2017-11-13 15:22:33.128  INFO 2384 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1315 ms
2017-11-13 15:22:33.255  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-13 15:22:33.258  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-13 15:22:33.259  INFO 2384 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-13 15:22:33.516  INFO 2384 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6ac13091: startup date [Mon Nov 13 15:22:31 CST 2017]; root of context hierarchy
2017-11-13 15:22:33.567  INFO 2384 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 15:22:33.568  INFO 2384 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 15:22:33.591  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:33.591  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:33.619  INFO 2384 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 15:22:34.011  INFO 2384 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-13 15:22:34.074  INFO 2384 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-11-13 15:22:34.080  INFO 2384 --- [           main] c.e.demo.SpringBootDemo1Application      : Started SpringBootDemo1Application in 2.588 seconds (JVM running for 2.872)
看到如下则说明启动成功,可以进入下一步操作

写个controller页面

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
public class HelloController {

	@RequestMapping("word")
	public String HelloWord() {
		return "Hello Word";
	}

}

输入链接 http://127.0.0.1:8080/StringBoot/hello/word


访问成功

你在这里访问的项目名和端口号都在application.yml中,

server:
  port: 端口号
  contextPath: 项目名
访问成功后,最基础的springBoot的基础搭建完成



遇到的错误解决方法:

一、Maven 工程错误Failure to transfer org.codehaus.plexus:plexus-io:pom:1.0,Failure to transfer org.codehaus.plexus:plexus-archiver:jar:2.0.1

解决方法:

        1.先去掉Maven工程的maven特性,选中工程 鼠标右键-->Maven-->Disable Maven Nature. 此步骤后pom.xml错误消失

        2.为工程增加Maven特性,选中工程 鼠标右键-->Configure-->Convert to Maven Project.

经过上述步骤,Maven工程就正常了。

二、运行时报错: Could not open ServletContext resource [/mybatis-config.xml]
mybatis: 
  config-location: classpath:mybatis-config.xml
请注意,如果classpath没写就会报这个错误
三、访问项目时如果出现


类似的错误,在访问的controller和方法都没问题的情况下,请检查你的项目入口


是否你的项目入口类必须在Controller的上一层,正确的位置路径如下



项目git地址:git@gitee.com:xzxWord/SpringBoot.git










  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值