自定义springboot-starter

本文介绍了两种自定义Springboot-Starter的方式:主动方式是通过在`spring.factories`配置自动装配类,利用Spring的SPI机制;被动方式则需在启动类上使用`@Enable`注解配合`@Import`导入自动装配类。了解这两种方式有助于更灵活地定制Springboot应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义springboot-starter有两种方式,一种是主动方式,一种是被动方式

主动方式:

在META-INF/spring.factories里面定义好自动装配的类。这样引入后就会加载自动装配的类,这是springboot的spi的机制,是模仿java 的spi。

被动方式:

       通过@Enable里面定义好@Import然后将自动装配的类定义好在里面。然后调用者需要在启动类上加上@Enable**来使用,否则自动装配不会生效。

下面主要演示第一种情况

1.引入基本依赖

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

2.定义属性配置类

@ConfigurationProperties("custom")
public class CustomProperties {

    private Integer age = 0;

    private String name = "defaultName";

    public Integer getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

3.定义一个普通的java 类

public class CustomPerson {

    private Integer age;

    private String name;

    public Integer getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

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

4.定义自动装配类 

@Configuration
@ConditionalOnClass({CustomPerson.class})
@EnableConfigurationProperties(CustomProperties.class)
public class CustomAutoConfiguration {

    @Autowired
    private CustomProperties customProperties;

    @Bean
    public CustomPerson customPerson(){
        CustomPerson customPerson = new CustomPerson();
        customPerson.setName(customProperties.getName());
        customPerson.setAge(customProperties.getAge());
        return customPerson;
    }
}

5. 通过maven打包到本地

6.其他项目可以引入依赖

<dependency>
            <groupId>com.example</groupId>
            <artifactId>demo-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值