栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

手写一个简单的SpringBoot Starter

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手写一个简单的SpringBoot Starter

手写一个简单的SpringBoot Starter

首先通过maven建立一个空项目;

建立好一个空的项目以后进行一个pom.xml 文件的导入

   
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            
            true
        
    

然后进行一个文件的建立

目录结构如上图;
首先我们先建立对应的文件然后对TestConfiguration进行编写

//标记为配置类
@Configuration
//启动配置属性
@EnableConfigurationProperties(TestProperties.class)
@ConditionalOnClass(TestService.class)
@ConditionalOnProperty(prefix = "test", value = "enabled", matchIfMissing = true)
public class TestConfiguration {
    @Autowired
    TestProperties testProperties;

    @Bean
    public  TestService TestService(){
        TestService service = new TestService();
        service.setName(testProperties.getName());
        return service;
    }

}

然后对TestProperties文件进行编写

@ConfigurationProperties(prefix = "test")
public class TestProperties {
    private static final String DEFAULT_NAME = "lht";

    private String name = DEFAULT_NAME;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

然后对TestService文件进行编写

public class TestService {

    private String name ;
    public String hello(){
        return "starter-name:"+getName();
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

上面写好以后,在 resources 文件夹下创建 META-INF/spring.factories 文件,通过上面的代码,Spring Boot 在启动的时候就是读取该文件下的配置类,从而将 Bean 加载到容器中。

org.springframework.boot.autoconfigure.EnableAutoConfiguration= 
  com.lht.TestConfiguration

然后通过mvn install 进行一个打包。

在新建maven工程
将自定义的starter进行导入`

   
            org.example
            test-starter
            1.0-SNAPSHOT
   

然后建立一个SpringBoot的启动类

@SpringBootApplication
@RestController
public class StarterTestApplicationTest{

    @Autowired
    TestService testService;

    @GetMapping("/a")
    public String index(){
        System.out.println(testService.getName());
        return testService.getName();
    }

    public static void main(String[] args) {
        SpringApplication.run(StarterTestApplicationTest.class, args);
    }
}

在application.yml中进行属性的配置

test:
  name: 111111

然后启动项目 对这个路径进行访问:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号