自定义启动器

自定义启动器

一般定义两个项目:启动器项目,自动配置项目
一个项目只是引入自动配置项目坐标,让其他项目作为启动器引入,这样间接引入了个人的自动配置项目。
另一个项目才是真正写自动配置的

步骤:
1-编写业务功能类

public class HelloService {

    HelloProperties helloProperties;

    public HelloProperties getHelloProperties() { return helloProperties; }
    public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; }

    public String sayHellAtguigu(String name){
        return helloProperties.getPrefix()+"-" +name + helloProperties.getSuffix();  // 使用配置文件中的相关配置
    }
}

2-编写properties配置类【@ConfigurationProperties(prefix = "xxx")】引入配置:读取配置文件


@ConfigurationProperties(prefix = "xiaoai.hello")
public class HelloProperties {

    private String prefix;
    private String suffix;

    public String getPrefix() { return prefix;}
    public void setPrefix(String prefix) { this.prefix = prefix;}
    public String getSuffix() { return suffix;}
    public void setSuffix(String suffix) {this.suffix = suffix; }
}

3-定义自动配置类(加【@Configuration】)
可加相关条件注解【@Conditionalxxx】如:@ConditionalOnwebApplication web应用才生效
加【@EnableConfigurationProperties(xxxProperties.class)】使配置属性类生效

在自动配置类中可以做相依业务: 如通过@Bean注解把相关实例注入到ioc容器中。

@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class) 引入配置类
public class HelloServiceAutoConfiguration {

    @Autowired
    HelloProperties helloProperties; // 自动注入配置类实例

    @Bean
    public HelloService helloService(){
        HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;
    }
}

4-自动配置类生效需在【MATE-INF/spring.factories】下添加

org.springframework.boot.autoconfigure.Enab1eAutoConfiguration=\
自动配置类全路径

5-配置项目安装到maven仓库中
5-自定义启动器项目安装到maven仓库中
6-其他项目通过maven引入自定义启动器坐标

如以上例子:在其他项目引入该启动器配置后可以自动注入HelloService实例调用sayHellAtguigu方法使用配置文件中的相关

posted @ 2021-01-09 15:21  小艾影  阅读(198)  评论(0编辑  收藏  举报