2020-11-29springboot自定义stater

一、搭建环境
1、创建一个空项目
2020-11-29springboot自定义stater_第1张图片
2、分别创建启动器模块和自动配置模块
(1)启动器只是传递作用,故创建一个maven工程即可,并在其中导入自动配置模块。

  <dependencies>
      <dependency>
           <groupId>my-spring-boot-autoconfigure</groupId>
           <artifactId>my-spring-boot-autoconfigure</artifactId>
           <version>0.0.1-SNAPSHOT</version>
       </dependency>
    </dependencies>

(2)自动配置模块需要编写自动配置类,故采用springboot较好
任意自动配置类都需要先配置springboot启动器,导入spring-boot-starter

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

二、自定义配置文件类、组件类、自动配置类

1、自定义配置文件类

@ConfigurationProperties(prefix = "my.hello")
public class Mypeoperties {
    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;
    }
}

2、组件类

public class HelloService {
    private Mypeoperties mypeoperties;

    public HelloService(Mypeoperties mypeoperties) {
        this.mypeoperties = mypeoperties;
    }

    public Mypeoperties getMypeoperties() {
        return mypeoperties;
    }

    public void setMypeoperties(Mypeoperties mypeoperties) {
        this.mypeoperties = mypeoperties;
    }

    public String sayHello(String name) {
        return mypeoperties.getPrefix()+name+mypeoperties.getSuffix();
    }
}

3、自动配置类

@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(Mypeoperties.class)
public class MyAutoCongigure {
    @Autowired
    Mypeoperties mypeoperties;
    @Bean
    public HelloService gethelloService(){
        return new HelloService(mypeoperties);
    }
}

三、打包

必须先打包自动配置类,否则启动器打包会找不到自动配置的依赖包
2020-11-29springboot自定义stater_第2张图片
四、使用
导入启动器包即可

<dependency>
	<groupId>my-spring-boot-starter</groupId>
	<artifactId>my-spring-boot-starter</artifactId>
	<version>1.0-SNAPSHOT</version>
</dependency>

你可能感兴趣的:(学习笔记,spring,boot)