把Spring boot整个项目作为库给第三方调用
其实也非常简单,只要三步就可以实现:
- 在工程里面添加
spring-boot-autoconfigure和spring-boot-configuration-processor依赖包。
- 在工程里面添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.4.5</version>
<optional>true</optional>
</dependency>
- add 自动配置类,关键添加
@AutoConfiguration和@ComponentScan("com.wewetea.open.demoadmin.**")替换成自己的项目包路径
- add 自动配置类,关键添加
package com.wewetea.open.demoadmin;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@AutoConfiguration
@ComponentScan("com.wewetea.open.demoadmin.**")
public class DemoConfig {
}
- 3.有两种方式实现,采用配置和采用注解,均可实现。
配置:
①新建src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,注意是在src/main/resources/目录下,再新建两个目录META-INF/spring/,再创建文件org.springframework.boot.autoconfigure.AutoConfiguration.imports即可。
在这个文件中,把你需要暴露的类,声明一下就可以。
com.wewetea.open.demoadmin.DemoConfig
这样,第三方引入你的包,就会自动加载。
②注解配置,新建一个注解,关键添加@Import({DemoConfig.class})就可以了。
package com.wewetea.open.demoadmin;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DemoConfig.class})
public @interface EnableDemoClient {
}
使用的时候,在自己的启动类中,添加@EnableDemoClient一下就可以了。
示例参考:
package com.wewetea.open.mytest;
import com.wewetea.open.CustomService;
import com.wewetea.open.demoadmin.DemoConfig;
import com.wewetea.open.demoadmin.EnableDemoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDemoClient
public class MytestApplication implements CommandLineRunner {
@Autowired
private CustomService customService;
// @Autowired
// private DemoConfig demoConfig;
public static void main(String[] args) {
SpringApplication.run(MytestApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
customService.doSomething();
}
}
以上三步,是自动把包作为注解提供自动装配。当然,你也可以每个自己去加载和new对象出来,这就是普通的maven加载库包没有区别了。这里,当然是采用自动装配了。主要的应用场景,把自己的库,作为第三方maven引入,降低耦合依赖。
注意:以上都是在Spring boot 3.x 版本进行的,其它版本,操作会有不同。
本文来自博客园,作者:刘文江,转载请注明原文链接:https://www.cnblogs.com/liuwenjiang/p/18899202

浙公网安备 33010602011771号