springboot自定义场景启动器starter的简单步骤。

1:创建一个空的工程,添加两个web或者springboot模块:lisi-springboot-starter     lisi-springboot-starter-autoconfigurer

具体命名参照场景启动器命名规则。一个是starter,一个是starter的自动配置类。

2:在lisi-springboot-starter 的pom.xml文件中导入autoconfigurer的相关依赖

<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>lisi-springboot-starter-autoconfigurer</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

 

3:开始编写 lisi-springboot-starter-autoconfigurer中的相关service、properties以及config配置类

      pom文件引入spring-boot-starter依赖,所有的启动器的必须步骤。

      3.1 编写一个xxxProperties类,@ConfigurationProperties(prefix = "lisi.hello")

@ConfigurationProperties(prefix = "lisi.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.2  编写一个service方法

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();
    }
}

3.3 编写相关的配置类

@Configuration   //声明该类为配置类
@ConditionalOnWebApplication //webapp可以使用该方法
@EnableConfigurationProperties(HelloProperties.class) //配置类中的参数类型
public class HelloServiceAutoConfiguration {

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

3.4 resources目录下新建一个MATE-INF文件夹,创建spring.factories文件。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
//这一行为自动注入的配置类的全路径类名
com.lisi.starter.HelloServiceAutoConfiguration

-------------------lisi-springboot-starter     lisi-springboot-starter-autoconfigurer的相关配置和内容完毕。

4.新建一个简单的测试项目

4.1 pom文件引入lisi-springboot-starter的依赖

4.2 写一个简单的controller方法调用helloservice,输出到浏览器

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String hello(){
        return helloService.sayHello("haha");
    }
}

4.3 配置相关的properties属性值

lisi.hello.prefix=aaa
lisi.hello.suffix=bbb     -----输出到浏览器------> aaa-haha-bbb

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值