个人学习Spring @Enable 模块驱动(一.注解驱动实现)笔记

本文围绕Spring @Enable模块驱动展开,介绍其按实现分为注解驱动和接口编程两种方式。着重探讨注解驱动实现,通过查看Spring Framework中DelegatingWebMvcConfiguration.class源码,给出示例,成功实现注解驱动的@Enable模块驱动,还提及下篇将实现接口编程方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Spring @Enable 模块驱动(一.注解驱动实现)

相信很多小伙伴都使用过Spring,而且经常看到使用Spring定义的一些注解,比如@EnableFeignClients,@EnableZuulProxy,@EnableEurekaServer,使用这些注解就可以激活相对应得模块,看到这里好奇心大的小伙伴,一定想知道为什么打这么一个注解就可以激活相应的模块,今天我们来讨论下这些注解背后的故事。

@Enable模块驱动,按照其实现分为注解驱动 接口编程 所以下面我们就来看下这两种方式实现

  1. 基于注解驱动实现@Enable模块

首先我们去找个Spring Framework中的例子来看一看

相信用过@Import的小伙伴都知道它的作用,我们去看看DelegatingWebMvcConfiguration.class的源码看看它究竟在干嘛

根据它的注释,代码和注解可以看出这是一个@Configuration类,这种实现方式,相当于给我们提供了一个很好的例子。所以下面我们也来实现一个自己的@Enable模块驱动(注解驱动实现)

package com.example.demo.annotation;


import com.example.demo.configurations.EatConfiguration;
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EatConfiguration.class)
public @interface EnableEat {
}
package com.example.demo.configurations;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;

@Configurable
public class EatConfiguration {

    @Bean
    public String eatRice(){
        return "i can eat rice";
    }
}
package com.example.demo;

import com.example.demo.annotation.EnableEat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

@EnableEat
@Slf4j
@Configuration
public class DemoApplication {

    public static void main(String[] args) {
        //构建Annotation配置驱动Spring上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //注册当前引导类到Spring的上下文
        context.register(DemoApplication.class);
        //启动上下文
        context.refresh();
        String eatRice = context.getBean("eatRice", String.class);
        log.info("result==================:[{}]", eatRice);
        //关闭上下文
        context.close();
    }

}

如图所示我们成功的实现注解驱动实现的@Enable模块驱动,

在下篇笔记中我们将实现基于接口编程实现@Enable模块。如有错误欢迎各位大佬指出,谢谢,

参考书籍:SpringBoot编程思想

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值