spring_springboot_自定义SpringbootStarter&Bean的装配方式

本文详细介绍了如何自定义Springboot Starter,包括单个Bean和批量Bean的装配方式,以及条件装配策略。同时讲解了创建第三方Starter的步骤,如服务类创建、参数配置和加载方式。最后,还阐述了如何在项目中引用第三方Starter。

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

自定义SpringbootStarter

Bean的装配方式

1. 单个Bean的装配

(1) @Configuration + @Bean 注解

package h.learn.config;

import h.learn.service.StudentService;
import h.learn.service.impl.StudentServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author huang
 * @since 2023/7/27
 */
@Configuration
public class RegisterWayByAnnoBean {
   

    @Bean
    public StudentService studentService() {
   
        return new StudentServiceImpl();
    }
}

2. 批量Bean的装配

(1) @Configuratioin + @Bean + @Bean + …

package h.learn.config;

import h.learn.service.StudentService;
import h.learn.service.impl.StudentServiceImpl;
import h.learn.service.impl.StudentServiceImpl2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author huang
 * @since 2023/7/27
 */
@Configuration
public class RegisterWayByAnnoBean {
   

    @Bean
    public StudentService studentService() {
   
        return new StudentServiceImpl();
    }

    @Bean
    public StudentService studentService2() {
   
        return new StudentServiceImpl2();
    }
}

(2) 通过@Configuration +@ComponentScan('包路径') 扫描包路径下,类上加上了【@Controller+@Service+@Component+@RestController】注解的类。
①启动类只扫描配置类所在包,和controller所在包
②需要的类上加上service 上述注解
③创建配置类,@Configuration +@ComponentScan('需要扫描的包路径')

package h.learn.application;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(value = {
   "h.learn.controller","h.learn.config"})
@Slf4j
public class HLearnRegisterWayOfBeanApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(HLearnRegisterWayOfBeanApplication.class,args);
        log.info("HLearnRegisterWayOfBeanApplication 启动成功");
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值