Spring Boot 的基础使用 eclipse下创建一个spring boot项目

eclipse下创建一个spring boot项目

一、安装STS插件

要在eclipse使用spring boot创建项目,必须先安装STS(Spring Tool Suite (STS) for Eclipse),如果网速给力的话可以选择在线安装,否则建议选择离线安装。

 

1.离线安装

第一个问题:准确的找到eclipse版本对应的STS插件,例如:

eclipse-Mars.4.5.2–>springsource-tool-suite-3.7.3RELEASE-e4.5.2-updatesite.zip

eclipse-neno.4.6–>springsource-tool-suite-3.7.3RELEASE-e4.6-updatesite.zip 

到官网https://spring.io/tools/sts/all 找到你本机Eclipse版本对应的STS版本,并下载压缩包,或者选择。

 

查看自己的eclipse版本

1. 找到Eclipse的解压目录就是你的Eclipse.exe 所在的目录

2. 找到 .eclipseproduct 文件双击打开 如图:

 


eclipse安装SpringSource Tool Suite(sts-eclipse)插件包括在线安装离线安装 
打开网页:http://spring.io/tools/sts/all 
可以看到: 

 

eclipse上 离线安装 SpringSource Tool Suite for eclipse插件:

运行eclipse--Help--Install New Software...

点击Add 

 

随便输入插件名称: sts-eclipse或sts, 选择SpringSource Tool Suite的zip包(可不解压) 

 

选择与IDE相关的项, 并去掉Contact all update…前面的勾选, 然后下一步 

 

直接下一步 

 

直接下一步 

 

接受协议, 点击Finish 

 

等待安装完成 

 

提示:you are installing software that contains content  the authenticty or validity of this software cannot be established do you  want to continue with the installation(您正在安装包含内容的软件,该软件的真实性或有效性无法建立,您是否想继续安装。) 点击继续。

已安装完成, 点击YES立即重启eclipse使sts-eclipse插件生效 

 

重启eclipse后可以看到可以创建spring项目了 

 

至此, 完成eclipse4.6.2下离线安装SpringSource Tool Suite(sts-eclipse)插件。

2.在线安装

eclipse上 在线安装 SpringSource Tool Suite for eclipse插件:

运行eclipse--Help--Install New Software...

 

剩余步骤同离线安装。 

.创建Spring Boot项目

1)创建项目,file-->New-->other-->Spring Boot -->选择Spring starter Project。填写跟项目相关的各种信息,然后Next:

 

选择需要的Dependency,然后Next:

 

最后"Finish",就开始下载jar包了,这个过程需要的时间比较长。加载完成后 如图:

 

、介绍

web开发是开发中至关重要的一部分,Web开发的核心内容主要包括内嵌Servlet和Spring MVC开发。Spring Boot提供了大量页面模版引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,Spring Boot中 推荐使用Thymeleaf作为页面模版引擎,因为Thymeleaf提供了完美的Spring MVC的支持。 

实战

1. 修改pom.xml文件 替换 <dependencies/>依赖项

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-cache</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

<version>1.3.6.RELEASE</version>

</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>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.4.1</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.3.1</version>

</dependency>

<!--支持使用 JDBC 访问数据库-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

        </dependency>

        <!--Json Support-->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.1.43</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid</artifactId>

<version>1.1.0</version>

</dependency>

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>

<dependency>

<groupId>org.apache.tomcat</groupId>

<artifactId>tomcat-jdbc</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<dependency>

           <groupId>javax.servlet</groupId>

           <artifactId>javax.servlet-api</artifactId>

           <scope>provided</scope>

        </dependency>

<dependency>

           <groupId>javax.servlet</groupId>

           <artifactId>jstl</artifactId>

        </dependency>

         <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-tomcat</artifactId>

           <scope>provided</scope>

       </dependency>

       <dependency>

           <groupId>org.apache.tomcat.embed</groupId>

           <artifactId>tomcat-embed-jasper</artifactId>

           <!-- <scope>provided</scope> -->

       </dependency>

      <!--  <dependency>

        <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-freemarker</artifactId>

</dependency> -->

</dependencies>

2. 设置全局配置文件

 springBoot支持两种方式的配置文件(二选其一即可)

propertiesyml

      配置上下文路径为  /test

      配置端口为:8081

properties的配置格式

server.context-path=/test 

server.port=8081

yml的配置格式

server: context-path: /test 

port: 8081

注意:yml的配置时冒号后面必须加一个空格;推荐使用yml格式的配置方式

 

application.properties配置:

server.port=8081

spring.datasource.url=jdbc:mysql://192.168.1.103:3306/patentdb?useUnicode=true&characterEncoding=utf-8

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#页面热加载 开发时关闭缓存,不然没法看到实时页面

spring.thymeleaf.cache = false

 

application.yml配置:

server:

# context-path: /test

  port: 8081

spring:

  thymeleaf:

        cache: false

  profiles:

    active: prod

  datasource:

    driver-class-name: com.mysql.jdbc.Driver

    url: jdbc:mysql://192.168.1.103:3306/patentdb?useUnicode=true&characterEncoding=utf-8

    username: root

password: root

 如果是本地数据库   改成url: jdbc:mysql://localhost:3306/自己数据库名?useUnicode=true&characterEncoding=utf-8

3. 写代码

Spring Boot通常有一个名为*Application的入口类,入口类里有一个main方法,这个main方法其实就是一个标准的Java应用的入口方法。在main方法中使用SpringApplication.run,启动Spring Boot应用项目。 

在入口类AppleApplication中,写入下面代码:

package com.example.demo;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.log4j.Logger;

import org.apache.tomcat.jdbc.pool.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

 

 

@SpringBootApplication

@MapperScan("com.example.demo.mapper")

public class DemoApplication{

 private static Logger logger = Logger.getLogger(DemoApplication.class);

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

logger.info("============= SpringBoot Start Success =============");

}

 

    //DataSource配置

    @Bean

    @ConfigurationProperties(prefix="spring.datasource")

    public DataSource dataSource() {

        return new DataSource();

    }

 

    //提供SqlSeesion

    @Bean

    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

 

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(dataSource());

 

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

 

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));

 

        return sqlSessionFactoryBean.getObject();

    }

 

    @Bean

    public PlatformTransactionManager transactionManager() {

        return new DataSourceTransactionManager(dataSource());

    }

 

}

 

resources目录下创建mybatis配置文件UserMapperConfig.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.example.demo.mapper.UserMapper">

 

    <select id="getAllUser" resultType="com.example.demo.domain.User">

        select * from groups;

    </select>

 

</mapper>

 

在包com.example.demo下,新建一个名为domainpackage,添加一个类User

 

package com.example.demo.domain;

 

public class User {

    private int id;

    private String group_name;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getGroup_name() {

return group_name;

}

public void setGroup_name(String group_name) {

this.group_name = group_name;

}

    

 

}

 

 

在包com.example.demo下,新建一个名为mapperpackage,添加一个类UserMapper

 

package com.example.demo.mapper;

 

import java.util.List;

 

import com.example.demo.domain.User;

 

public interface UserMapper {

    List<User> getAllUser();

 

}

 

在包com.example.demo下,新建一个名为servicepackage,添加一个类UserSercice和一个名为implpackage ,在其下添加一个类UserSerciceimpl.

 

package com.example.demo.service;

 

import com.example.demo.domain.User;

 

import java.util.List;

 

public interface UserService {

    List<User> getAllUser();

}

 

package com.example.demo.service.Impl;

 

import com.example.demo.mapper.UserMapper;

import com.example.demo.domain.User;

import com.example.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import java.util.List;

@Service

public class UserServiceImpl implements UserService {

    @Autowired

    UserMapper userMapper;

 

    @Override

    public List<User> getAllUser() {

        return userMapper.getAllUser();

 

    }

}

 

在包com.example.demo下,新建一个名为controller的package,添加一个类TestBootController

 

package com.example.demo.controller;

import com.example.demo.domain.User;

import com.example.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

 

 

@Controller

public class TestBootController {

    @Autowired

    private UserService userService;

 

    @RequestMapping(value = "/demo",method = RequestMethod.GET)

    public String getAllRole(Model model) {

        List<User> allUsers = userService.getAllUser();

        model.addAttribute("allUsers",allUsers);

        return "index";

    }

 

}

 

resources目录下创建log4j.properties:

 

log4j.rootLogger=INFO, stdout,weblog

######################### logger ##############################

 

log4j.appender.stdout = org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout = org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.conversionPattern = %d [%t] %-5p %c - %m%n

 

log4j.logger.weblog=INFO, weblog

log4j.additivity.weblog=true;

log4j.appender.weblog=org.apache.log4j.DailyRollingFileAppender

log4j.appender.weblog.File=../logs/weblog.log

log4j.appender.weblog.layout=org.apache.log4j.PatternLayout

log4j.appender.weblog.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

 

 

templates下创建index.html页面:

 

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

    <meta charset="UTF-8"/>

    <title>Title</title>

</head>

<body>

<h1>Hello World</h1>

<table>

<tr>

<th>

序号

</th>

<th>

权限

</th>

</tr>

 <tr th:each="prod : ${allUsers}">

      <td th:text="${prod.id}"></td>

      <td th:text="${prod.group_name}"></td>

 </tr>

</table>

</body>

</html>

 

最后运行Run As--》Spring Boot:

 

 

 百度云源码地址:https://pan.baidu.com/s/1oiAksf4PbZqQGtfDq6Bwqw   密码:n9qq

源码只支持HTML页面   如果要使用jsp页面  删除pom。xml中:

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

 修改application.properties文件

 

 完美!

 

 

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页