SpringBoot3.x自定义封装starter实战
1.创建一个普通的maven项目;
2.导入自动配置依赖
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>3.2.0</version> </dependency>
|
3.编写实体类信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package org.pt.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "user") public class User { private String name; private String email; private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", email='" + email + '\'' + ", age=" + age + '}'; } }
|
@ConfigurationProperties 注解在 Spring Boot 中用于将外部配置绑定到 JavaBean。在这里,prefix = “user” 表示以 user 开头的配置将会绑定到 JavaBean 类的字段上
3.定义自动配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package org.pt.config;
import org.pt.service.UserService; 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({User.class}) @EnableConfigurationProperties({User.class}) public class UserAutoConfiguration {
@Bean @ConditionalOnMissingBean public User user(){ return new User(); }
}
|
@EnableConfigurationProperties({User.class}) 表示告诉 Spring Boot 应该处理名为 User
的类,并将其配置绑定到外部配置;
@ConditionalOnMissingBean 是 Spring Boot 中的一个条件注解,它表示只有当容器中不存在某个特定类型的 bean 时,才会创建被注解的 bean
@ConditionalOnClass 是 Spring Boot 中的一个条件注解,它表示只有当类路径上存在指定的类时,才会创建被注解的 bean 或配置
4.创建imports配置文件,把需要自动装载的类配置上
自动配置类必须放进下面的文件里才算自动配置类META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
5.使用mvn package install打包项目
6.在其他模块引入打包后的项目
7.新模块中注入对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.example.springbootconfiguration.controller;
import jakarta.annotation.Resource; import org.pt.config.User; import org.pt.service.UserService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class UserController {
@Resource public User user;
@GetMapping("/getUser") public String getUser(){ return user.toString(); } }
|
1 2 3 4
| spring.application.name=spring-boot-configuration user.email=3548297839@qq.com user.age=18 user.name=pt
|
9.启动项目访问
源码地址:https://github.com/Breeze1203/JavaAdvanced/tree/main/springboot-demo/user-spring-boot-starter