自定义起步依赖
工程demo1 加入工程demo 2 的依赖(起步依赖),直接注入即可使用
工程demo2 (自定义起步依赖) User对象交给spring容器管理
demo2起步依赖构建
- 添加spring父工程
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.8.RELEASE</version> </parent>
- 添加springboot起步依赖,不是web起步依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
- 创建配置类、创建User 交给spring容器管理
@Configuration public class UserAutoConfiguration { @Bean @ConditionalOnMissingBean // 没有此bean时,才执行此操作 public User user(){ return new User("小黄"); } }
- 在resource下创建 META-INF / spring.factories 文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.example.config.UserAutoConfiguration\
- spring.factories 中以key=value 形式配置 【 key 是固定的;value 是你自定义配置类的全路径】
demo 结构:


当有多个配置类要导入时,可以通过自定义一个注解统一导入
package org.example.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({RoleConfig.class, UserConfig.class})
public @interface EnableUserConfig {
}
本文介绍了如何在Spring Boot项目中创建自定义起步依赖,包括引入spring-boot-starter-parent,添加非web起步依赖,创建配置类管理User Bean,并通过spring.factories文件注册配置类。此外,还展示了如何通过自定义注解统一导入多个配置类。
630

被折叠的 条评论
为什么被折叠?



