Spring-starter 的自动装配Demo

13 篇文章 0 订阅
3 篇文章 0 订阅

Spring-starter 的自动装配Demo

此文属于借鉴文,太久了现在才发博客,找不到借鉴地址了,原博主看到回复定加借鉴地址,谢谢!

在借鉴的项目上修改配置为枚举,以防手写错误导致SpringBean的IOC注入失败,问题。

Spring-starter编写

pom.xml的maven坐标

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- 这个是用来提示用的-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.4.1</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <optional>true</optional>
        </dependency>
		<!-- 这里可不引入,但使用这个项目的maven要引入-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>
        <!-- 这里可不引入,但使用这个项目的maven要引入也可以fastjson和gson二选一引入,
			但是只引入一个的话就只能用这个一个,也不能通过yml配置另一个-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>
    </dependencies>

Properties配置类编写这里我的类名为:ZkqProperties

import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * @Description 这是自定义配置类
 * @Author 张凯强
 * @Date Created in 2021/9/6
 * @E-mail 862166318@qq.com
 */
@Data
@ConfigurationProperties(prefix = ZkqProperties.ORMAT_PREFIX, ignoreUnknownFields = true)
public class ZkqProperties {
    public static final String ORMAT_PREFIX = "zkq.json";
    /**
     * 这是配置用那个包
     */
    private ZKQTYPE type = ZKQTYPE.FASTJSON;

    // 这里用的是枚举,为了配置的时候可选,以防手输入错误
    public enum ZKQTYPE {
        /**
         * 这是alibaba.fastjson包
         */
        FASTJSON,
        /**
         * 这是个谷歌google.GSON 包
         */
        GSON
    }

}

这是字段的提醒:
在这里插入图片描述
这是配置的时候,枚举可选,避免手输入:
在这里插入图片描述
生成实例toJson代理接口代码

/**
 * @Description 这是生成实例的代理接口 
 * @Author 张凯强
 * @Date Created in 2021/5/17
 * @E-mail 862166318@qq.com
 */
public interface FormatProcessor {
    /**
     * 定义一个格式化的方法
     *
     * @param obj
     * @param <T>  这里的泛型可以用 Object 类型替换,自营研究
     * @return
     */
    <T> String format(T obj);
}

这是连个不同的包生成实例的代码:

import com.alibaba.fastjson.JSON;
import com.zkq.zkqdemo.processor.FormatProcessor;

/**
 * @Description 只是fastjson 实例化代码
 * @Author 张凯强
 * @Date Created in 2021/5/17
 * @E-mail 862166318@qq.com
 */
public class FastjsonFormatProcessor implements FormatProcessor {
    public <T> String format(T obj) {
        return "FastjsonFormatProcessor:"+ JSON.toJSONString(obj);
    }
}
import com.google.gson.Gson;
import com.zkq.zkqdemo.processor.FormatProcessor;
/**
 * @Description 这是 Gson 实例化代码
 * @Author 张凯强 
 * @Date Created in 2021/5/17
 * @E-mail 862166318@qq.com
 */
public class GsonFormatProcessor implements FormatProcessor {
    public <T> String format(T obj) {
        Gson gson = new Gson();
        return "GsonFormatProcessor:" + gson.toJson(obj);
    }
}

这是实例化ZkqFormatTemplate 并注入Spring IOC 的类

import com.zkq.zkqdemo.processor.FormatProcessor;
import com.zkq.zkqdemo.processor.impl.FastjsonFormatProcessor;
import com.zkq.zkqdemo.processor.impl.GsonFormatProcessor;
import com.zkq.zkqdemo.template.ZkqFormatTemplate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
 * @Description 这SpringIOC配置类 一下注解不多做解释,如有不懂,可自己百度
 * @Author 张凯强
 * @Date Created in 2021/5/18
 * @E-mail 862166318@qq.com
 */
@Import(FormatAutoConfiguration.class) // 这个Import注解是将这个类注入SirngIOC容器中
@EnableConfigurationProperties(ZkqProperties.class) 
@Configuration
public class ZkqFormatConfiguration {

    @Bean
    public ZkqFormatTemplate helloFormatTemplate(ZkqProperties zkqProperties, FormatProcessor formatProcessor){
        // 判断配置文件中的配置是否为 fastjson 如果是就实例化 fastjson 实例
        if (ZkqProperties.ZKQTYPE.FASTJSON.equals(zkqProperties.getType())) {
            return new ZkqFormatTemplate(new FastjsonFormatProcessor());
        }
        // 判断配置文件中的配置是否为 GSON 如果是就实例化 GSON 实例
        if(ZkqProperties.ZKQTYPE.GSON.equals(zkqProperties.getType())){
            return new ZkqFormatTemplate(new GsonFormatProcessor());
        }
        // 这个是如果什么也没配置就是去SpringIOC容器中去找,这里不会走到这里因为我们已经给配置文件初始化过fastjson,
        // 如果想要走到这里就不要给配置类初始化值就OK了
        return new ZkqFormatTemplate(formatProcessor);
    }
}

这是SpringIOC 实例化 FormatProcessor 子类的代码

import com.zkq.zkqdemo.processor.FormatProcessor;
import com.zkq.zkqdemo.processor.impl.FastjsonFormatProcessor;
import com.zkq.zkqdemo.processor.impl.GsonFormatProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
 * @Description 这是SpringIOC自动实例化FormatProcessor实现类的代码,一下不懂可百度,也可评论,看到及回复
 * @Author 张凯强
 * @Date Created in 2021/5/18
 * @E-mail 862166318@qq.com
 */

@Configuration
public class FormatAutoConfiguration {
    @ConditionalOnClass(name = "com.alibaba.fastjson.JSON") // 判断这个包是否存在
    @Bean
    @Primary // alibaba.fastjson优先
    public FormatProcessor fastjsonFormat(){
        return new FastjsonFormatProcessor();
    }
    @ConditionalOnClass(name = "com.goole.gson.Gson") // 判断这个包是否存在
    @Bean
    public FormatProcessor gsonFormat(){
        return new GsonFormatProcessor();
    }
}

最后写Spring自动注入配置文件 在 resources 下创建 META-INF 文件夹,在META-INF文件夹下创建spring.factories 文件,这个是spring自动注入的扫描文件

这个路径是Spring 写死的:
在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.zkq.zkqdemo.config.ZkqFormatConfiguration

配置要自动注入的类路径我的是com.zkq.zkqdemo.config.ZkqFormatConfiguration 这个要根据自己项目的路径配置
如果不想用这种自动的方式,手动的也可以用@Import(ZkqFormatConfiguration.class)

最后一点要求maven 里install安装一下,把这个当前项目安装的本地仓库,不然地没有的话,下面的测试maven坐标引进去报错,导致无法测试

Spring-starter-test编写

pom.xml 的Maven 坐标

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <optional>true</optional>
    </dependency>
	<!-- 这个是我们上面构建的本地坐标项目 -->
    <dependency>
        <groupId>com.zkq</groupId>
        <artifactId>zkqdemo-spring-boot-starter</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

Spring 测试代码

import com.zkq.zkqdemo.config.ZkqProperties;
import com.zkq.zkqdemo.template.ZkqFormatTemplate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class ZkqtestStarterTestApplicationTests {

    @Autowired
    ZkqFormatTemplate zkqFormatTemplate;
    @Autowired
    ZkqProperties zkqProperties;

    @Test
    void contextLoads() {
        Map<String, Object> map = new HashMap<>();
        map.put("id",1L);
        map.put("name","张凯强");
        map.put("age",25);
        String formatUser = zkqFormatTemplate.doFormat(map);
        // 输出toJson 结果
        System.out.println(formatUser);
        // 输出当前配置的是那个值,这里默认的FASTJSON,上面说过,不配置默认FASTJSON
        System.out.println(zkqProperties.getType());
    }

}

这是什么也没配置的结果:
在这里插入图片描述

FastjsonFormatProcessor:{"name":"张凯强","id":1,"age":25}
FASTJSON

这是配置 gson 的结果:
在这里插入图片描述

GsonFormatProcessor:{"name":"张凯强","id":1,"age":25}
GSON

这是配置 fastjson 的结果:(其实是和不配是一样的)
在这里插入图片描述

FastjsonFormatProcessor:{"name":"张凯强","id":1,"age":25}
FASTJSON

条件装配的注解扩展

Spring 定义的注解:
在这里插入图片描述

  • @ConditionalOnBean(Zkq.class)
    表示Spring Bean Factory 存在Zkq这个对象执行被注解的代码;@ConditionalOnMissingBean 相反;
  • @ConditionalOnClass(Zkq.class)
    表示 Zkq这个Java Bean 存在时执行被注解的代码;@ ConditionalOnMissingClass 相反;
  • @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
    检查云平台 配个CloudPlatform 枚举使用
  • ConditionalOnExpression(“${zkq.autoconfig.enabled}”)
    利用SpEL表达式 判断是否执行被注解代码

待更新。。。

到此结束,大神勿喷,欢迎交流!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值