自定义SpringBoot-Starter

使用SpringBoot-Starter的好处:

开发者只需要依赖相应功能的Starter,Spring Boot就能自动扫描并加载相应的模块,将模块所需的依赖整合起来并对模块内的Bean根据条件进行自动配置,无需做过多的配置和依赖。例如我想要在SpringBoot项目中集成SpringMVC,那么我只需要加入spring-boot-starter-web的依赖,不需要其他依赖和配置,就可以使用SpringMVC,省去了之前很多的配置操作。

原理:

1、SpringBoot 在启动时会扫描项目所依赖的starter包中寻找 resources/META-INF/spring.factories 文件

2、根据 spring.factories配置加载AutoConfigure类。

3、根据 @Conditional注解的条件,进行自动配置并将Bean注入Spring Context 上下文当中。

 

1、先构建一个SpringBoot项目

修改parent,主类就可以删除了

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starters</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>

 

 

HelloWorld-spring-boot-starter   

也可以使用spring-boot-starter,里面有spring-boot-autoconfigure , 但是会导入一些不必要的jar包

spring-boot-configuration-processor 可用来读取配置文件,可根据配置文件中的值来创建Bean

 1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starters</artifactId>
		<version>2.0.6.RELEASE</version>
	</parent>
	<groupId>com.hao.helloworld</groupId>
	<artifactId>HelloWorld-spring-boot-starter</artifactId>
	<version>0.0.1</version>
	<name>HelloWorld-spring-boot-starter</name>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<!-- <version>3.3</version> -->
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

2、业务类:HelloWorldService

package com.hao.helloworld.service;

public class HelloWorldService {
	private String name ;
	
	public HelloWorldService(String name) {
		this.name = name ;
	}
	
	public String hello() {
		return "hello ," + name  ;
	}
	
	
}

 

3、配置类:HelloWorldStarterAutoConfigure

package com.hao.helloworld.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hao.helloworld.service.HelloWorldService;

@Configuration
@ConditionalOnClass(HelloWorldService.class)
public class HelloWorldStarterAutoConfigure {

	@Value("${helloworld.service.name}")
	private String name  ;
	
	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(value = "helloworld.service.enabled", havingValue = "true")
	HelloWorldService HelloWorldService() {
		return new HelloWorldService(name);
	}
}



@ConditionalOnClass(HelloWorldService.class)    当classpath下发现HelloWorldService类的情况下进行自动配置。

@Value("${helloworld.service.name}")    读取配置文件中的值

@ConditionalOnMissingBean     不存在该Bean时创建

@ConditionalOnProperty(value = "helloworld.service.enabled", havingValue = "true")   配置文件中       helloworld.service.enabled 的值为true时创建Bean

 

 

4、手动在src/main/resources下创建/META-INF/spring.factories 文件

内容如下

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.hao.helloworld.config.HelloWorldStarterAutoConfigure

5、/META-INF/ 创建additional-spring-configuration-metadata.json

格式参考如下:

{
  "properties": [
    {
      "name": "spring.cloud.nacos.config.encode",
      "type": "java.lang.String",
      "defaultValue": "UTF-8",
      "description": "default encode for nacos config content."
    },
    {
      "name": "spring.cloud.nacos.config.prefix",
      "type": "java.lang.String",
      "defaultValue": "${spring.application.name}",
      "description": "the prefix of dataId, nacos config data meta info. dataId = prefix + '-' + ${spring.active.profile} + `.` + ${spring.cloud.nacos.config.file-extension}."
    },
    {
      "name": "spring.cloud.nacos.config.file-extension",
      "type": "java.lang.String",
      "defaultValue": "properties",
      "description": "the suffix of nacos config dataId, also the file extension of config content, only support properties now."
    },
    {
      "name": "spring.cloud.nacos.config.shared-dataids",
      "type": "java.lang.String",
      "description": "the dataids for configurable multiple shared configurations , multiple separated by commas ."
    },
    {
      "name": "spring.cloud.nacos.config.refreshable-dataids",
      "type": "java.lang.String",
      "description": "refreshable dataids , multiple separated by commas ."
    },
    {
      "name": "spring.cloud.nacos.config.ext-config",
      "type": "java.util.List",
      "description": "a set of extended configurations ."
    },
    {
      "name": "spring.cloud.nacos.config.enabled",
      "type": "java.lang.Boolean",
      "defaultValue": true,
      "description": "enable nacos config or not."
    }
  ]
}

加上这个文件后,在application.properties中就会有自动提示,不会有黄线禁告。

 

构建成jar包后在其他项目使用。

 

2、测试

pom.xml

<dependency>
            <groupId>com.hao.helloworld</groupId>
            <artifactId>HelloWorld-spring-boot-starter</artifactId>
            <version>0.0.1</version>
        </dependency>

再引入其他相关依赖

application.properties

server.port=80

helloworld.service.enabled=true
helloworld.service.name=zhangsan

 

直接注入 HelloWorldService类

package com.xxxxxx.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hao.helloworld.service.HelloWorldService;

@RestController
public class HelloTest {

	@Autowired
	private HelloWorldService HelloWorldService ;
	
	@RequestMapping("/test")
	public String test() {
		return HelloWorldService.hello(); 
	}
}

 

 

测试结果: 

 

当helloworld.service.enabled=false 时, 启动会报错;

Description:

Field HelloWorldService in com.xxxxx.demo.controller.HelloTest required a bean of type 'com.hao.helloworld.service.HelloWorldService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
    - Bean method 'HelloWorldService' in 'HelloWorldStarterAutoConfigure' not loaded because @ConditionalOnProperty (helloworld.service.enabled=true) found different value in property 'enabled'


Action:

Consider revisiting the entries above or defining a bean of type 'com.hao.helloworld.service.HelloWorldService' in your configuration.


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值