使用SpringBoot自定义一个starter启动包,超详细,Java工作经验6年

注入userProperties,获取对应配置文件的具体值

注入需要注入的类,注入的类需加注解@Repository或@Component、@Service、@Controller

package com.xjt.demo.conf;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

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

@ConditionalOnClass(UserService.class)

@EnableConfigurationProperties(UserProperties.class)

public class UserAutoConfiguration {

@Autowired

UserProperties userProperties;

@Bean

@ConditionalOnMissingBean(UserService.class)

public UserService userService(){

//将userService的字段赋值并注入到ioc容器

return new UserService(userProperties.getUserName(), userProperties.getHobby());

}

}

UserService

==============================================================================

测试类,从新项目导入注入UserService测试类方法

package com.xjt.demo.conf;

import lombok.AllArgsConstructor;

import lombok.Data;

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot一个快速开发微服务的框架,它提供了大量的自动化配置和快速开发的工具。在Spring Boot中,我们可以使用Starter来快速集成一些常用的功能,如数据库、缓存、web等。而自定义Starter则可以让我们将自己的功能快速集成到Spring Boot中,下面是自定义Starter的流程: 1. 创建Maven项目 首先,我们需要创建一个Maven项目作为我们自定义Starter的项目。在项目的pom.xml中添加Spring Boot的依赖,以及其他需要集成的依赖。 2. 编写自动配置类 自动配置类是自定义Starter的核心,它负责将我们自定义的功能集成到Spring Boot中。在自动配置类中,我们可以使用@Conditional注解来判断是否需要进行配置。 3. 编写Starter类 Starter类是我们自定义Starter的入口,它负责将自动配置类注入到Spring容器中。在Starter类中,我们需要使用@EnableAutoConfiguration注解来启用自动配置。 4. 打和发布Starter 当我们完成了自动配置类和Starter类的编写后,我们需要将自定义Starter成jar,并发布到Maven仓库中,以便其他项目可以通过Maven依赖的方式使用我们的Starter。 5. 在项目中使用自定义Starter 在其他项目中使用自定义Starter非常简单,只需要在项目中的pom.xml中添加我们自定义Starter的依赖即可。Spring Boot会自动将我们的自定义Starter集成到项目中,并进行自动配置。 以上就是自定义Starter的流程,通过自定义Starter,我们可以将自己的功能快速集成到Spring Boot中,提高开发效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值