1.通过Maven新建项目,并导入依赖.
artifactId必须遵循自定义starter规则

<dependencies>
<!--自定义starter必须要引入的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
2.整体结构

HelloServiceImpl内容:
package com.firststar.service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Service//忘记加入 用Compent也可以 总之记住加入就可以 这样才能配置到IOC容器
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello() {
return "hello,FirstStar!!!!!";
}
}
HelloServiceAutoConfiguration内容:
package com.firststar;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class HelloServiceAutoConfiguration {
}
这个类是配置类,注册@Configuration注解类到Spring容器
如果@Configuration注解的类上有@ComponentScan注解
如果@ComponentScan配置了包,则使用@ComponentScan配置的包
如果@ComponentScan没有配置包,则扫描其注解的类的包(扫描ConfigrationBean所在的包)
spring.factories:
#=后边的根据实际情况配置类的全路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.firststar.HelloServiceAutoConfiguration
(!!!注意resources在main下面~~ 我当时配置错误就一直导致Service注入错误,有点蠢:)
本文介绍了如何使用Maven创建一个自定义的Spring Boot Starter。首先,需要在pom.xml中引入`spring-boot-autoconfigure`依赖。接着,定义服务类HelloServiceImpl,并使用@Service注解。然后,创建配置类HelloServiceAutoConfiguration,使用@Configuration和@ComponentScan注解。最后,在资源目录下的spring.factories文件中配置启用自动配置的类。注意,资源配置错误可能导致Service注入失败。
1170

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



