springboot之手写starter配置类


前言

前序文章 springboot自动装配和统一配置分析中,提到自动装配是基于Spring的spi机制,封装自动装配类,提供给spring进行统一管理。
为了显而易见的展示该依赖是自动装配类,有了如下规范,包名中含有starter关键词,springboot自带的自动装配类不以starter结尾,如spring-boot-starter-web,第三方配置类以starter结尾,如xxl-job-starter。
基于springboot的spi机制,我们手写一个简单的starter,来切身感受一下starter的神奇之处


一、手写starter

1、创建maven工程,引入springboot依赖

<?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>org.sjl</groupId>
    <artifactId>sjl-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot.version>2.0.4.RELEASE</spring-boot.version>
    </properties>

    <!--内置属性-->
    <dependencies>
        <!--Spring Boot 自动配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${spring-boot.version}</version>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

2、编写相关业务类

1、实体类Student

package org.sjl.model;

public class Student {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2、数据访问层StudentMapper

package org.sjl.mapper;

import org.sjl.model.Student;

public class StudentMapper {

    public Student getStudent(){
        Student student = new Student();
        student.setName("starter");
        student.setAge(1);
        return student;
    }
}

3、业务逻辑层

package org.sjl.service;

import org.sjl.mapper.StudentMapper;
import org.sjl.model.Student;
import org.springframework.beans.factory.annotation.Autowired;

public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public Student getStudent(){
        return studentMapper.getStudent();
    }

}

3、编写自动装配类

1、创建Configuration配置类

package org.sjl.config;

import org.sjl.mapper.StudentMapper;
import org.sjl.service.StudentService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// 表示application配置中存在sjl.starter.enable属性且值为true的时候才会进行自动装配
@ConditionalOnProperty(name = "sjl.starter.enable", havingValue = "true")
@Configuration
public class StudentConfiguration {

    @Bean
    @ConditionalOnMissingBean // 当不存在该bean,则创建bean对象
    public StudentService studentService(){
        return new StudentService();
    }

    @Bean
    @ConditionalOnMissingBean
    public StudentMapper studentMapper(){
        return new StudentMapper();
    }

}

2、创建 META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.sjl.config.StudentConfiguration

二、使用装配类

1、打包starter

通过maven install 打包好配置类

2、引入starter

        <dependency>
            <groupId>org.sjl</groupId>
            <artifactId>sjl-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

3、编写application.yml

sjl:
  starter:
    enable: true

4、启动springboot并进行测试验证

package org.example;

import org.sjl.service.StudentService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class AutoApplication {
    public static void main(String[] args) {
        ApplicationContext ac = SpringApplication.run(AutoApplication.class, args);
        StudentService studentService = ac.getBean(StudentService.class);
        System.out.println(studentService.getStudent());
    }
}

5、控制台输出结果

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.0)

2024-06-11 19:58:50.345  INFO 27324 --- [           main] org.example.AutoApplication              : Starting AutoApplication using Java 1.8.0_161 on PF2YXEAZ with PID 27324 (D:\JavaProject\study\springboot-auto-demo\target\classes started by sujinglun in D:\JavaProject\study\springboot-auto-demo)
2024-06-11 19:58:50.347  INFO 27324 --- [           main] org.example.AutoApplication              : No active profile set, falling back to 1 default profile: "default"
2024-06-11 19:58:50.802  INFO 27324 --- [           main] org.example.AutoApplication              : Started AutoApplication in 0.858 seconds (JVM running for 2.044)
Student{name='starter', age=1}

Process finished with exit code 0

我们可以看到,我们没有测试项目没有进行任何bean的注册下,就可最直接使用studentService进行调用,因为我们编写的starter装配类已经帮我们做好了自动装配

总结

springboot在如此巧妙的设计下,大大的优化了bean的注入过程,这个思想很值得我们去思考,并学会举一反三。

  • 25
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值