Skip to content

Latest commit

 

History

History
120 lines (91 loc) · 2.9 KB

03.深入浅出SpringBoot的核心原理(下).md

File metadata and controls

120 lines (91 loc) · 2.9 KB

自定义Starter

1.format-spring-boot-starter

1.定义功能文件

public interface FormatProcessor {

    public <T> String format(T obj);
}
public class JsonFormatProcessor implements FormatProcessor{

    @Override
    public <T> String format(T obj) {
        return "JsonFormatProcessor:" + JSON.toJSONString(obj);
    }
}
public class StringFormatProcessor implements FormatProcessor{
    @Override
    public <T> String format(T obj) {
        return "StringFormatProcessor:" + Objects.toString(obj);
    }
}
public class HelloFormatTemplate {
    private FormatProcessor formatProcessor;

    private HelloProperties helloProperties;

    public HelloFormatTemplate(FormatProcessor formatProcessor, HelloProperties helloProperties) {
        this.formatProcessor = formatProcessor;
        this.helloProperties = helloProperties;
    }

    public <T> String doFormat(T obj) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("begin:Execute format:").append("<br/>");
        stringBuilder.append("HelloProperties:").append(formatProcessor.format(helloProperties.getInfo())).append("<br/>");
        stringBuilder.append("Object format result:").append(formatProcessor.format(obj)).append("\n");
        return stringBuilder.toString();
    }
}

2.使用@Configuration注入功能bean

@Configuration
public class FormatAutoConfiguration {

    @ConditionalOnMissingClass(value = "com.alibaba.fastjson.JSON")
    @Primary
    @Bean
    public FormatProcessor stringFormat() {
        return new StringFormatProcessor();
    }

    @ConditionalOnClass(name = "com.alibaba.fastjson.JSON")
    @Bean
    public FormatProcessor jsonFormat() {
        return new JsonFormatProcessor();
    }
}

3.使用ConfigurationProperties添加Properties配置

@ConfigurationProperties(prefix = HelloProperties.HELLO_FORMAT_PREFIX)
public class HelloProperties {

    public static final String HELLO_FORMAT_PREFIX="moremind.hello.format";

    private Map<String, Object> info;

    public Map<String, Object> getInfo() {
        return info;
    }

    public void setInfo(Map<String, Object> info) {
        this.info = info;
    }
}

4.定义SpringBoot自动装配类

@Import(FormatAutoConfiguration.class)
@EnableConfigurationProperties(HelloProperties.class)
@Configuration
public class HelloAutoConfiguration {

    @Bean
    public HelloFormatTemplate helloFormatTemplate(FormatProcessor formatProcessor, HelloProperties helloProperties) {
        return new HelloFormatTemplate(formatProcessor, helloProperties);
    }
}

5.在resource/META-INF目录下添加spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.moremind.formatspringbootstarter.auto.HelloAutoConfiguration

添加spring加载时自动装配的bean。

6.mvn install 安装jar包