2019-04-18 Springboot Starter

2019-04-18  本文已影响0人  Jocelyn_b0e1

参考:https://www.cnblogs.com/yuansc/p/9088212.html
STEP1:创建一个SpringBoot 项目,并添加下面两个依赖到pom.xml文件当中。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
</dependencies>

STEP2: 编写Service类
···
public class StarterService {
private String config;

public StarterService(String config) {
    this.config = config;
}

public String[] split(String separatorChar) {
    return StringUtils.split(this.config, separatorChar);
}

}
···
STEP3:编写配置文件读取类

@ConfigurationProperties("example.service")
public class StarterServiceProperties {
    private String config;
    
    public void setConfig(String config) {
        this.config = config;
    }
    
    public String getConfig() {
        return config;
    }
 }

STEP4:编写AutoConfigure类

@Configuration
@ConditionalOnClass(StarterService.class)
@EnableConfigurationProperties(StarterServiceProperties.class)
public class StarterAutoConfigure {

    @Autowired
    private StarterServiceProperties properties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")
    StarterService starterService (){
        return new StarterService(properties.getConfig());
    }

}

解释一下代码中用到的几个注解:
•@ConditionalOnClass,当classpath下发现该类的情况下进行自动配置。
•@ConditionalOnMissingBean,当Spring Context中不存在该Bean时。
•@ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true"),当配置文件中example.service.enabled=true时。

上一篇下一篇

猜你喜欢

热点阅读