srpingboot 自定义 start

自动配置工程

  1. 绑定配置文件,上逼格的 start 都支持自定义配置,我们也装像点~~

    @ConfigurationProperties("cyrus.hello") 
    public class CyrusHelloProperties {
        
        // 绑定配置文件 cyrus.hello.username 属性
        private String username;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    }
    
  2. start 核心业务功能

    // 这里没有 @Configuration,因为要自动配置
    public class HelloService {
    
        @Autowired
        private CyrusHelloProperties cyrusHelloProperties;
    
        public String sayHello(String username){
            return cyrusHelloProperties.getUsername() + "你好";
        }
    
    }
    
  3. start 自动配置

    @Configuration
    @EnableConfigurationProperties(CyrusHelloProperties.class)
    public class CyrusHelloAutoConfiguration {
    
        @ConditionalOnMissingBean(HelloService.class)
        @Bean
        public HelloService helloService(){
            return new HelloService();
        }
    }
    

start 工程

  1. resource/META-INF 下创建 spring.factories 文件,文件内容如下

    # Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.cyrus.hello.autoconfigure.CyrusHelloAutoConfiguration
    
  2. pom 引入自动配置工程,引入 start 自动引入其所需依赖

    <dependencies>
        <dependency>
            <groupId>curus-hello</groupId>
            <artifactId>cyrus-hello-spring-boot-autoconfigure</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
    

工程结构

posted @ 2024-07-07 17:09  CyrusHuang  阅读(1)  评论(0编辑  收藏  举报