spring boot starter 入门示例

36 篇文章 0 订阅
16 篇文章 1 订阅

示例一

依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
</dependencies>
业务实现
//HelloService.java
public class HelloService {
    private String name;
    private String addr;
    public HelloService(String name,String addr){
        this.name = name;
        this.addr = addr;
    }
    public String sayHello(){
        return String.format("我叫%s,我来自%s", this.name,this.addr);
    }
}

// helloProperties
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "hello")
public class HelloPorperties {
    private String name;
    private String addr;
}
自动配置实现
// 自动配置类
import com.snail.hello.starter.service.HelloService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(HelloPorperties.class)  //自动注入HelloPorperties
public class HelloServeicAutoConfiguration {
    private HelloPorperties helloPorperties;
    public HelloServeicAutoConfiguration(HelloPorperties helloPorperties){
        this.helloPorperties = helloPorperties;
    }
    // 使用HelloPorperties的配置属性创建出HelloService对象并加入到spring容器中。
    @ConditionalOnMissingBean
    @Bean
    public HelloService helloService(){
        return new HelloService(this.helloPorperties.getName(),this.helloPorperties.getAddr());
    }
}
#在resource目录中创建 META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.snail.hello.starter.config.HelloServeicAutoConfiguration
使用
  1. 创建springboot工程,并引入此starter

  2. 在配置文件中配置如下内容

    hello:
      addr: jiangxi
      name: luolf
    
  3. 在需要使用HelloService的地方直接注入即可使用,如下:

    import com.snail.hello.starter.service.HelloService;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    public class HelloControl {
    
        @Resource
        private HelloService helloService;
    
        @RequestMapping("/sayHello")
        public String sayHell(){
            return helloService.sayHello();
        }
    }
    
    // 访问sayHello 即可调用到helloService.sayHello()方法。
    

示例二

依赖
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
</parent>

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
</dependencies>
业务实现
// MyLog 注解
package com.snail.hello.starter.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {

    String desc() default "";
}

// 日志拦截器,继承HandlerInterceptorAdapter
public class MyLogInterceptor extends HandlerInterceptorAdapter {

    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    // 方法执行前拦截,记录开始时间.
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isInterceptMethod(handler)) {
            startTimeThreadLocal.set(System.currentTimeMillis());
        }
        return true;
    }

    private boolean isInterceptMethod(Object handler) {
        if(!(handler instanceof HandlerMethod)){
            return false;
        }
        return ((HandlerMethod) handler).getMethod().getAnnotation(MyLog.class) != null;
    }

    // 方法执行后拦截,记录记录时间,并打印日志信息.
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (isInterceptMethod(handler)) {
            Method method = ((HandlerMethod) handler).getMethod();
            MyLog myLog = method.getAnnotation(MyLog.class);
            System.out.println(String.format("请求URL:%s,请求方法:%s,方法描述:%s,方法执行时间:%s"
                    , request.getRequestURI()
                    , method.getDeclaringClass().getName() + "." + method.getName()
                    , myLog.desc()
                    , (System.currentTimeMillis() - startTimeThreadLocal.get()) + "ms"));
        }
    }
}
自动配置实现
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyLogInterceptor());
    }
}
#在resource目录中创建 META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.snail.hello.starter.config.MyLogAutoConfiguration
使用
@RestController
public class HelloControl {

    @Resource
    private HelloService helloService;

    @RequestMapping("/sayHello")
    @MyLog(desc = "测试方法")  // 增加日志注解.
    public String sayHell(){
        return helloService.sayHello();
    }
}

// 执行方法后会打印出日志:请求URL:/sayHello,请求方法:com.snail.control.HelloControl.sayHell,方法描述:测试方法,方法执行时间:32ms
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring BootSpring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring BootSpring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛_snail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值