根据自动装配原理在Springboot项目中自定义starter,并实现热插拔技术,自定义@enable

根据自动装配原理在Springboot项目中自定义starter,并实现热插拔技术

自定义starter

简单步骤

  1. 创建项目,并引入autoconfigure依赖,根据自己的需要选择spring-boot的版本号
  • maven项目:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-autoconfigure</artifactId>
  <version>[自己选择spring-boot的版本号]</version>
</dependency>
  • gradle
implementation 'org.springframework.boot:spring-boot-autoconfigure:指定的版本号'
  1. 创建自己注入的组件/bean/service的java类
@ConfigurationProperties(prefix = "mystarter")
public class MyStarterBean {

	private Integer id;

	private String name;

	// getting/setting 省略
}
  1. 创建自动装配Class
@Configuration
public class MyAutoConfiguration {

	@Bean
	public MyStarterBean myStarterBean(){
		return new MyStarterBean();
	}
}
  1. 在项目的resource目录下新建META-INF目录,并创建一个名为spring.factories的文件
    在文件中
 # Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.chenglj.starter.MyAutoConfiguration

使用测试

  1. 直接引入自定义的starter依赖
  2. 试着在配置文件中配置属性
mystarter.id = 250000
mystarter.name = cheng
  1. 测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@RunWith(SpringRunner.class)
public class MySpringBootTest {

	@Resource
	MyStarterBean myStarterBean;

	@Test
	public void test(){
		System.out.println(myStarterBean.getId()+"="+myStarterBean.getName());
	}
}

优化(热插拔技术)

  1. 创建一个标记类

public class MyStarterBeanMarker {

}
  1. 创建一个enable注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({MyStarterBeanMarker.class})
public @interface EnableRegisterMyStarter {
}

3.在自动装配类中添加添加条件

@Configuration
@ConditionalOnBean(MyStarterBeanMarker.class) //只有容器中有MyStarterBeanMarker这个bean时才会扫描这个配置类
public class MyAutoConfiguration {

	@Bean
	public MyStarterBean createBean(){
		return new MyStarterBean();
	}
}
  1. 测试
    在SpringBoot启动主类加上自定义的注解@EnableRegisterMyStarter ,不添加则无法注入MyStarterBean。
@SpringBootApplication
@EnableRegisterMyStarter
public class TestApplication {
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值