springboot搭建项目

springboot搭建项目

===================================

pom文件中引入springboot父类依赖,所有springboot项目都必须依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>

配置application文件

#端口
spring:
    port: 8080

#数据库连接
spring:
    datasource:
        url:jdbc:oracle:thin:@localhost:1521:serverName
        userName: userName
        password: password
        driver-calss-name: oracle.jdbc.driver.OracleDriver
        type: com.alibaba.druid.pool.DruidDataSource

配置启动类

package com.cccc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

依赖springMVC,开启springmvc框架

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency><!-- springboot用webflux代替web -->
    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-webflux</artifactId>        <version>2.0.3.RELEASE</version>    </dependency>

依赖mybatis,集成mybatis框架

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

依赖数据jdbc驱动,与数据库连接

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>

依赖第三方数据源Druid,配置数据源信息

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

配置数据源和事务

package com.cccc.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@Data
@MapperScan(basePackages = "com.cccc.mapper", sqlSessionFactoryRef = "sessionFactory")
public class DruidConfig {

    private String url;
    private String userName;
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;

    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }

    @Bean("sessionFactory")
    public SqlSessionFactory sessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.cccc.pojo");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean("sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

依赖配置文件驱动,可添加也可不添加此依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

依赖springboot测试框架

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>

test示例

package com.cccc;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AirwayServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testList() {
        List<User> list = userService.getList();
        //如果插入成功 num为1,否则提示插入失败
        Assert.assertTrue("num不为1,插入失败", num == 1);
    }

}

springboot集成通用mapper框架,仅针对单表操作

        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>

springboot集成swagger2文档框架

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

swagger2配置类

package com.cccc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cccc"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("新项目使用swagger2框架")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .build();
    }
}

swagger2示例,访问http://localhost:8080/swagger-ui.html

package com.cccc.controller;

import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "基础信息-特殊旅客类别")
public class SpecialPassengerTypeController {
    private Logger logger = LoggerFactory.getLogger(SpecialPassengerTypeController.class);

    @Value("${server.port}")
    private String port;

    @Autowired
    private UserService userService;

    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询用户信息", notes = "支持模糊查询")
    @ApiImplicitParam(name = "param", value = "查询条件对象", required = false, dataType = "User", paramType = "query")
    public String getSpecialList(User param){
        return "success";
    }
}

添加监控中心actuator

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

在application中配置监控所有权限

management:
  endpoints:
    web:
      exposure:
        include: "*"

访问http://localhost:8080/actuator/beans查看spring中所有bean的信息

访问http://localhost:8080/actuator/autoconfig查看springboot所有自动配置

访问http://localhost:8080/actuator/configprops查看所有配置属性

访问http://localhost:8080/actuator/mappings查看所有映射路径

访问http://localhost:8080/actuator/env查看环境变量

服务注册consul

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

application中配置consul信息

spring:
  application:
    name: config-param
  cloud:
    consul:
      host: localhost
      port: 8500
      enable: true
      discovery:
        healthCheckPath: /actuator/health
        healthCheckInterval: 15s
        instance-id: config-param

启动类配置@EnableDiscoveryClient

启动consul服务器 consul agent -dev,访问http://localhost:8500

 

springboot admin管理服务

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server-ui</artifactId>
            <version>2.0.1</version>
        </dependency>

启动类添加 @EnableAdminServer,访问http://localhost:port

添加boot admin的配置

spring:
  application:
    name: config-param
  boot:
    admin:
      client:
        url: http://localhost:8080

服务调用feign,springboot2.0依赖的feign为openfeign

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>

启动类添加@EnableFeignClients,配置feign调用接口

application.yml添加配置,开启feign调用

feign:
  hystrix:
    enabled: true
package com.cccc.feign;

import com.cccc.dto.ConfigParamDTO;
import com.cccc.fallback.ConfigTypeServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@FeignClient(value = "data-service", path = "/config", fallback = ConfigServiceFallback.class)
public interface ConfigService {

    @PostMapping(value = "/getList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    String getType(@RequestBody Config param);
}

fallback降级

package com.cccc.fallback;

import org.springframework.stereotype.Component;

@Component
public class ConfigServiceFallback implements ConfigService {
    @Override
    public String getType(Config param) {
        return "调用feign失败";
    }
}

断路器hystrix

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>

 启动类添加@EnableCircuitBreaker

Hystix示例

package com.cccc.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.cccc.dto.ConfigParamDTO;
import com.cccc.feign.ConfigTypeService;
import com.cccc.mapper.ConfigParamMapper;
import com.cccc.pojo.ConfigParam;
import com.cccc.service.ConfigParamService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private ConfigMapper mapper;

    @Override
    @HystrixCommand(fallbackMethod = "hystrix")
    public List<Config> getList(int s) {
        return mapper.getList();
    }

    public List<Config> hystrix(int s) {
        List<Config> list = Lists.newArrayList();
        return list;
    }

}

springcloud链路跟踪工具 ,路径调用全过程,集成zipkin框架

配置zipkin服务server

        <dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-server</artifactId>
            <version>2.9.4</version>
        </dependency>
        <dependency>
            <groupId>io.zipkin.java</groupId>
            <artifactId>zipkin-autoconfigure-ui</artifactId>
            <version>2.9.4</version>
        </dependency>

在启动类添加@EnableZipkinServer开启zipkin服务

配置服务到zipkin

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

配置application的zipkin地址信息

spring:
  zipkin:
    base-url: http://localhost:8888
    locator:
      discovery:
        enabled: true
  sleuth:
    sampler:
      percentage: 0.1

springboot读取配置文件properties,读取自定义配置文件

1、使用@PropertySource("classpath:user.properties") + @Value("${}"),前提必须有属性的set方法,spring 中的bean才有初始化配置属性 ,注入取对象@Autowired

package com.cccc.service.impl;

import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@Data
public class PropertyServiceImpl implements PropertyService {

    @Value("${stu.age}")
    private String age;

    @Value("${stu.name}")
    private String name;

    @Override
    public String getProperties() {
        return "addr = " + name + " --> age = " + age;
    }
}

stu.properties文件

stu.name=lisi
stu.age=18

 

2、@PropertySource("classpath:stu.properties") + @ConfigurationProperties(prefix = "stu"),前提必须有属性的set方法,spring 中的bean才有初始化配置属性,以注入方式取bean @Autowired

package com.cccc.service.impl;

import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
public class PropertyServiceImpl implements PropertyService {

    private String age;

    private String name;

    @Override
    public String getProperties() {
        return "addr = " + name + " >>> age = " + age;
    }
}

3、新建配置类 + 注入

package com.cccc.Config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
@Configuration
public class UserConfig {
    private String name;
    private String age;
}

引用,注入进来

package com.cccc.service.impl;

import com.cccc.Config.UserConfig;
import com.cccc.service.PropertyService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource("classpath:stu.properties")
@ConfigurationProperties(prefix = "stu")
@Data
public class PropertyServiceImpl implements PropertyService {

    @Autowired
    private UserConfig userConfig;

    @Override
    public String getProperties() {
        return "addr = " + userConfig.getName() + " >>> age = " + userConfig.getAge();
    }
}

原文地址:https://www.cnblogs.com/antlord/p/9249539.html

时间: 2024-10-10 22:42:39

springboot搭建项目的相关文章

SpringBoot 学习:(一)快速搭建项目

一.简介 从 Spring Boot 项目名称中的 Boot 可以看出来,Spring Boot 的作用在于创建和启动新的基于 Spring 框架的项目.它的目的是帮助开发人员很容易的创建出独立运行和产品级别的基于 Spring 框架的应用.Spring Boot 会选择最适合的 Spring 子项目和第三方开源库进行整合.大部分 Spring Boot 应用只需要非常少的配置就可以快速运行起来. Spring Boot 包含的特性如下: 创建可以独立运行的 Spring 应用. 直接嵌入 To

手把手教你从零开始搭建SpringBoot后端项目框架

原料 新鲜的IntelliJ IDEA.一双手.以及电脑一台. 搭建框架 新建项目 打开IDE,点击File -> New Project.在左侧的列表中的选择Maven项目,点击Next. 填写GroupId和ArtifactId 什么是GroupId和ArtifactId?大家可以参考一下google出来的定义,可以参考一下. GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构. ArtifactID就是项目的唯一的标识符,实际对应项目的名称

springBoot 搭建web项目(前后端分离,附项目源代码地址)

springBoot 搭建web项目(前后端分离,附项目源代码地址) 概述 该项目包含springBoot-example-ui 和 springBoot-example,分别为前端与后端,前后端分离,利用ajax交互. springBoot-example-ui 前端html 技术:BootStrap + layer + jquery + css + html 该项目git地址:https://github.com/jiangcaijun/springBoot-example-ui sprin

SpringCloud从入门到进阶(四)——使用SpringBoot搭建微服务

内容 SpringBoot整合SpringCloud的Eureka.Zuul等组件,快速实现简单易懂且具有服务熔断.负载均衡的分布式架构1.0,体验微服务的魅力. 版本 IDE:IDEA 2017.2.2 x64 JDK:1.8.0_171 manve:3.3.3 SpringBoot:1.5.9.RELEASE SpringCloud:Dalston.SR1 适合人群 ?Java开发人员 说明 转载请说明出处:SpringCloud从入门到进阶(四)--使用SpringBoot搭建微服务 参考

[转]MVP+WCF+三层结构搭建项目框架

最近,我一直在重构之前做的一个项目,在这个过程中感慨万千.原先的项目是一个运用了WCF的C/S系统,在客户端运用了MVC模式,但MVC的View.Model耦合以及WCF端分布式欠佳等问题让我有了重构的想法,经过了一段时间的改造,逐渐形成了MVP+三层结构+WCF的面向服务的程序架构.在这里我把我的想法写成了一个例子,供大家参考. 在正式开始讲解之前,我必须得感谢Artech.代震军等诸多大虾,他们的文章给了我很大的启发. 我写的这个例子是关于博客管理的,逻辑很简单,就是用户发表文章.发表评论,

ASP.NET MVC搭建项目后台UI框架—7、统计报表

ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NET MVC搭建项目后台UI框架—4.tab多页签支持 ASP.NET MVC搭建项目后台UI框架—5.Demo演示Controller和View的交互 ASP.NET MVC搭建项目后台UI框架—6.客户管理(添加.修改.查询.分页) ASP.NET MVC搭建项目后台UI框架—7.统计报表 本节,我将通

ASP.NET MVC搭建项目后台UI框架—4、tab多页签支持

目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NET MVC搭建项目后台UI框架—4.tab多页签支持 ASP.NET MVC搭建项目后台UI框架—5.Demo演示Controller和View的交互 在点击左侧菜单中的选项时,我希望有Extjs.EasyUI等中类似的tab页签功能,因为这样可以支持多个页面的浏览,有时候我们可能需要同时打开多个页

ASP.NET MVC搭建项目后台UI框架—2、菜单特效

目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 上一篇,已经把整个项目的框框给搭建好了,但是还没有任何js效果实现.这一节,我就来说下关于菜单的特效实现.我需要的效果如下: 需求总结: 点击顶部菜单模块,左侧显示不同模块下面的菜单列表 点击左侧菜单选项,展开下面的子菜单,并折叠其它菜单模块,菜单图标折叠显示为+,展开显示为-. 1.先看下Top视图中代码: 2.在Top视图的head中添加如下js: <script sr

ASP.NET MVC搭建项目后台UI框架—9、服务器端排序

ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NET MVC搭建项目后台UI框架—4.tab多页签支持 ASP.NET MVC搭建项目后台UI框架—5.Demo演示Controller和View的交互 ASP.NET MVC搭建项目后台UI框架—6.客户管理(添加.修改.查询.分页) ASP.NET MVC搭建项目后台UI框架—7.统计报表 ASP.NE