默认情况下,springboot只自动加载项目main方法目录下的bean,对于依赖的jar包,并不会自动加载jar中的bean。所以有时候我们编写jar包给他人使用,需要完成jar包自动加载配置的功能,就需要编写start。
1、首先需要引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
2、编写相关bean初始化代码
@Data
public class AutoServer {
private String param1;
}
@Data
@Configuration
@ConditionalOnClass
@ConfigurationProperties(prefix = "test1")
public class MyAutoConfiguration {
private String param1="10";
@Bean
@ConditionalOnClass(AutoServer.class)
@ConditionalOnProperty(name="test1.param1",matchIfMissing = true)
public AutoServer autoServerResolver(){
AutoServer autoServer=new AutoServer();
autoServer.setParam1(param1);
return autoServer;
}
}
2、添加spring.factories
内容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example2.autoconfig.MyAutoConfiguration
4、编译打包
5、新项目中引入jar
<dependency>
<groupId>com.example2</groupId>
<artifactId>demo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/demo2-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
6、编写配置文件
test1:
param1: 11
7、在项目中使用bean
@Autowired
private AutoServer autoServer;
@RequestMapping("/test1")
public String test1(){
return "hello test "+autoServer.getParam1();
}