自定义starter

git 地址:https://gitee.com/ihate404/starter-demo.git

最近写代码时看到同事把部分额外功能抽取成了一个个starter,与核心业务代码分开。所以想来自己自定义一个starter,这里记录一下。

 

 我的demo里只有两个模块,一个是starter模块,一个测试starter的app模块 (多模块聚合的项目中,有子模块的记得改打包方式为pom) 

<packaging>pom</packaging>

1.自定义starter

starter里只用加入下面这个依赖 

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

在resources下增加META-INF/spring.factories文件,里面配置starter启动类

 

 starter里面随便写一个类 ,写一个测试方法

通过 @Bean 在启动类中把这个类的对象加到spring中。

在app模块中,只需要在pom中引入starter的依赖。再@Autowired 即可引入自定义的starter中定义的对象

2.@EnableConfigurationProperties 注解

@EnableConfigurationProperties(A.class)的作用就是如果 A 这个类上使用了 @ConfigurationProperties 注解,那么 A 这个类会与 xxx.properties 进行动态绑定,并且会将 A 这个类加入 IOC 容器中,并交由 IOC 容器进行管理

 

 可以在我的代码中看到  StarterConfiguration 并未加到 spring.factories中,却生效了 ,并从app模块的配置文件中获取了参数。正是因为这个注解。

遇到了一个问题,StarterConfiguration必须在HelloWorldController 的同一个包或者子包下才能引用。

 

posted @ 2022-11-29 10:18  下饭  阅读(84)  评论(0编辑  收藏  举报