springboot这几年能够迅速的普及,比spring最大的优势就是自动装配,不是配置类替代xml。在springboot项目中引入其他的jar包,但是其他jar包中的@Configuration,@Component等注解却不会被本应用所识别,因为工程默认只会识别本项目classpath类路径下的注解,但是springBoot也提供了自动装配的扩展机制。
下面就来写一个自动装配的demo。
先建一个springBoot项目作为我们即将引入的jar。
项目结构

pom依赖中引入解析自动装配解析器的依赖.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>先建一个配置类 MyProperties
@ConfigurationProperties(prefix = "custom")
@Data
public class MyProperties {
private String name;
private Integer age;
private String gender;
}
然后将配置类注册到spring, CustomAutoConfiguration.
@Configuration
@EnableConfigurationProperties({MyProperties.class})
public class CustomAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public MyProperties myProperties(){
MyProperties myProperties = new MyProperties();
myProperties.setName("缺失姓名");
myProperties.setAge(77);
myProperties.setGender("缺失性别");
return myProperties;
}
}
然后在resources下新建META-INF目录,在下面新建spring.factories文件,文件内容为指定自动配置的配置类.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.config.CustomAutoConfiguration
然后打成一个Jar包就可以给其他项目使用了。
在其他的项目里面引入该jar包,可以配置custom.name,custom.age,custom.gender等属性,这样就可以在项目中进行引用了。
版权声明:本文为weixin_41751625原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。