上篇文章我们主要讲了spring自动装配的原理,我们知道了springboot在启动的时候会自动去读.factories文件,在factories文件中,autoConfiguration对应的就是我们程序启动时自己预加载的类,另外我也提到了另外一个比较核心的注解,即@ConditionOnxxx。详情点击https://blog.csdn.net/qq_41907991/article/details/88704448


这篇文章我们主要分析下@ConditionOnxxx注解,以及自己实现一个starter。下面开始分析我们的@ConditionOnxxx注解。先看代码:

我们以@ConditionalOnMissingBean这个注解来分析原理:

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnMissingBean {....}

很明显,上面的核心注解就是@Conditional注解,我们接下来分析这个注解,直接上代码看效果

package com.study.spring.condition.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; /**
* @Author: dmz
* @Description:
* @Date: Create in 23:16 2019/3/25
*/
public class CatCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("what").equals("cat");
}
}
package com.study.spring.condition.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; /**
* @Author: dmz
* @Description:
* @Date: Create in 23:16 2019/3/25
*/
public class DogCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("what").equals("dog");
}
}

上面这两个类,是我自定义的两个条件

package com.study.spring.condition.model;

import com.study.spring.condition.condition.CatCondition;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component; /**
* @Author: dmz
* @Description:
* @Date: Create in 23:19 2019/3/25
*/
@Component
@Conditional({CatCondition.class})
public class Cat {
public Cat(){
System.out.println("猫来了,喵喵喵~~");
}
}
package com.study.spring.condition.model;

import com.study.spring.condition.condition.DogCondition;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component; /**
* @Author: dmz
* @Description:
* @Date: Create in 23:18 2019/3/25
*/
@Component
@Conditional({DogCondition.class})
public class Dog {
public Dog(){
System.out.println("dog 来了,汪汪汪~~~");
}
}

主要是为了通过条件控制我们这两个类的加载

what:cat

这是配置文件中的内容

package com.study.spring.condition;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class ConditionApplication { public static void main(String[] args) {
SpringApplication.run(ConditionApplication.class, args);
} }

这是启动类

启动程序,可以看到程序打印:

猫来了,喵喵喵~~

经过上面的程序我相信大家对这个@conditional注解已经有了一定的了解

接下来我们来实现我们的自定义starter

pom文件如下:

<?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-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.study.spring</groupId>
<artifactId>starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myAutoconfig-spring-boot-starter</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency> <!--为了生成spring-configuration-metadata.json-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

整体项目结构如下

package com.study.spring.starter.AutoConfig;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; /**
* @author dmz
* @date Create in 22:06 2019/3/23
*/
@Data
@ConfigurationProperties(prefix = "config")
public class Config {
private String name;
private Integer age;
}
package com.study.spring.starter.AutoConfig;

import com.study.spring.starter.service.MyService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* @author dmz
* @date Create in 21:24 2019/3/23
*/
@Configuration
@EnableConfigurationProperties(Config.class)
@ConditionalOnClass(MyService.class)
public class MyAutoConfig { @Bean
@ConditionalOnMissingBean(MyService.class)
public MyService getMyService() {
return new MyService();
}
}
package com.study.spring.starter.service;

import com.study.spring.starter.AutoConfig.Config;
import org.springframework.beans.factory.annotation.Autowired; /**
* @author dmz
* @date Create in 21:53 2019/3/23
*/
public class MyService { @Autowired
private Config config; public void say() {
System.out.println("自定义的starter来了,say:" + config.getName());
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*保留启动类,主要是为了执行maven的命令,
* 打包到我们的本地仓库
*/
@SpringBootApplication
public class StarterApplication{
public static void main(String[] args) {
SpringApplication.run(StarterApplication.class, args);
} }

spring.factories文件如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.study.spring.starter.AutoConfig.MyAutoConfig

测试代码如下:

<?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-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.study.spring</groupId>
<artifactId>starter-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>starter-test</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--引入我们的依赖-->
<dependency>
<groupId>com.study.spring</groupId>
<artifactId>starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

启动类:

package com.study.spring.startertest;

import com.study.spring.starter.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class StarterTestApplication implements ApplicationRunner { @Autowired
private MyService myService; public static void main(String[] args) {
SpringApplication.run(StarterTestApplication.class, args);
} @Override
public void run(ApplicationArguments args) throws Exception {
myService.say();
}
}

我们在测试项目中加了配置信息

config.name=zhangsan

运行结果如下:

  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE) 2019-03-27 00:09:52.995 INFO 19468 --- [ main] c.s.s.s.StarterTestApplication : Starting StarterTestApplication on DESKTOP-N88SU6M with PID 19468 (C:\Users\dell\Desktop\spring-master\starter-test\target\classes started by dell in C:\Users\dell\Desktop\spring-master)
2019-03-27 00:09:52.999 INFO 19468 --- [ main] c.s.s.s.StarterTestApplication : No active profile set, falling back to default profiles: default
2019-03-27 00:09:53.416 INFO 19468 --- [ main] c.s.s.s.StarterTestApplication : Started StarterTestApplication in 0.722 seconds (JVM running for 1.243)
自定义的starter来了,say:zhangsan Process finished with exit code 0

验证成功~~

项目github地址:https://github.com/daimingzhi/spring.git

spring学习笔记(六)自定义spring-boot-starter(2)的更多相关文章

  1. Spring学习笔记六:Spring整合Hibernate

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6785323.html  前言:整合概述 Spring整合Hibernate主要是把Hibernate中常用的S ...

  2. 【Spring学习笔记-MVC-15】Spring MVC之异常处理

    作者:ssslinppp       1. 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理 ...

  3. Spring学习笔记—最小化Spring XML配置

    自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bean的依赖关系. 自动 ...

  4. 【Spring学习笔记-0】Spring开发所需要的核心jar包

    spring开发所需要的核心jar 1. libs目录下的核心jar包: 2. common-logging-xxx.jar 来自为知笔记(Wiz) 附件列表

  5. Spring学习笔记五:Spring进行事务管理

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6776256.html  事务管理主要负责对持久化方法进行统一的提交或回滚,Spring进行事务管理即我们无需在 ...

  6. 【Spring学习笔记-MVC-2】spring导出Excel

    说明: 1.结合Spring MVC实现Excel导出功能: 2. 在MVC配置文件中配置Excel视图解析器: 需要的jar包 以poi开头的jar包都是必须的 web.xml <?xml v ...

  7. 【Spring学习笔记-5】Spring中的抽象bean以及bean继承

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  8. 【Spring学习笔记-MVC-16】Spring MVC之重定向-解决中文乱码

    概述 spring MVC框架controller间跳转,需重定向,主要有如下三种: 不带参数跳转:形如:http://localhost:8080/SpringMVCTest/test/myRedi ...

  9. 【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问

    作者:ssslinppp       参考链接: http://www.cnblogs.com/luxh/archive/2013/03/14/2959207.html  http://www.cnb ...

  10. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

随机推荐

  1. Python之利用jieba库做词频统计且制作词云图

    一.环境以及注意事项 1.windows10家庭版 python 3.7.1 2.需要使用到的库 wordcloud(词云),jieba(中文分词库),安装过程不展示 3.注意事项:由于wordclo ...

  2. 也谈如何实现bind、apply、call

    也谈如何实现bind.apply.call 我们知道,JavaScript的bind.apply.call是三个非常重要的方法.bind可以返回固定this.固定参数的函数包装:apply和call可 ...

  3. c语言中的引用使用

    最近在写一个图像处理的程序时候,遇到一些传参的问题,最后发现引用的效率高一些,在此提醒各位道友,多多关注引用的应用及使用. 1.在引用的使用中,单纯给某个变量取个别名是毫无意义的,不要为了耍酷而乱用, ...

  4. day23作业

    # 作业: # 1.把登录与注册的密码都换成密文形式 info = {"tom":"202cb962ac59075b964b07152d234b70"} def ...

  5. 杭电 How far away ?

    There are n houses in the village and some bidirectional roads connecting them. Every day peole alwa ...

  6. windows编译动态链接库,dll+lib的形式

    之前一直在linux上做开发,没怎么关注过windows上如何编译动态链接库.不过一直存疑,为什么windows上的动态链接库是.dll配合.lib使用的,这个又是怎么生成的呢,通过一段时间的查资料和 ...

  7. Linux学习笔记(八)权限管理命令

    权限管理命令 权限位含义 chmod chown chgrp umask默认权限 权限位含义 第1位代表文件类型 "-":普通文件 "b":块设备文件 &quo ...

  8. 通达OA任意用户登录 漏洞复现

    0x00 漏洞简介 通达OA国内常用的办公系统,使用群体,大小公司都可以,其此次安全更新修复的高危漏洞为任意用户登录漏洞.攻击者在远程且未经授权的情况下,通过利用此漏洞,可以直接以任意用户身份登录到系 ...

  9. [nodejs] 同步/异步创建多层目录

    背景 有时项目里需要同时创建多层目录的功能,但低版本的nodejs并没有提供快捷的api 尽管在v10.12.0版本 mkdir() 第二个参数支持recursive 参数,为true时能递归创建,但 ...

  10. PHP反序列化漏洞总结(二)

    写在前边 之前介绍了什么是序列化和反序列化,顺便演示了一个简单的反序列化漏洞,现在结合实战,开始填坑 前篇:https://www.cnblogs.com/Lee-404/p/12771032.htm ...