1. 程式人生 > >springboot搭建項目

springboot搭建項目

string javax -a cit true -s manager ray 配置文件

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();
    }
}

springboot搭建項目