自定义起步依赖
工程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 {
}