springboot自定义starter启动器

说明

命名规约

官方命名:

  • spring-boot-starter-xxx

自定义命名:

  • xxx-spring-boot-starter

步骤

1、在idea中新建一个普通Maven模块:Jing-spring-boot-starter

2、新建一个Springboot模块:JIng-spring-boot-starter-aoutoconfigure

3、在starter中导入autoconfigure的依赖

<dependency>
    <groupId>com.lili</groupId>
    <artifactId>jing-springboot-starter-autoconfig</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

4、编写一个类用来测试

@ConfigurationProperties(prefix = "com.lili")
public class HelloProperties {
    private String name;
    private int age;
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return this.age;
    }

    @Override
    public String toString() {
        return "HelloProperties{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class HelloService {
    private HelloProperties helloProperties;

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

    public HelloProperties getHelloProperties() {
        return helloProperties;
    }
    public void show(){
        System.out.println("你好,丽丽");
    }
}

5、编写一个配置类并注入bean进行测试

@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

6、在resources编写一个自己的META-INF\spring.factories,内容如下

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.lili.config.HelloServiceAutoConfiguration

7、新建一个Maven模块进行测试,需要导入自定义的启动器

        <!--导入自定义的测试器进行测试-->
        <dependency>
            <groupId>com.lili</groupId>
            <artifactId>jing-springboot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

8、编写Controller

@RestController
public class HelloController {
    @Autowired
    HelloService helloService;
    @RequestMapping("/helloStart")
    public HelloService getMessage(){
        return helloService;
    }
}

9、在properties里面可以给属性赋值

com.lili.name=张三
com.lili.age=23

10、运行然后访问

104

到这里,我们自己定义的starter就成功啦!

posted @   JamieChyi  阅读(25)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示