springboot进阶(3):Enable注解

前言

@Enable*注解
Springboot中提供了很多Enable开头的注解,这些注解用于动态的开启某些功能。而底层原理是使用了@Import注解导入了一些配置类,实现Bean的动态加载。

第一节、问题:引入一个jar能直接获取它的Bean吗

新建两个工程,用例子来说明

pojo工程

  1. 创建一个springboot模块(不选择任何组件)
    在这里插入图片描述
  2. 编写User
package com.it2.pojo.springbootenablepojo.pojo;
public class User {
}
  1. 编写UserConfig
package com.it2.pojo.springbootenablepojo.config;
import com.it2.pojo.springbootenablepojo.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
    @Bean
    public User user(){
        return new User();
    }
}
  1. 安装这个依赖到本地仓库 mvn install
    在这里插入图片描述

enable工程(引入pojo)

  1. 新建enable工程
    在这里插入图片描述
  2. 导入pojo依赖
<dependency>
            <groupId>com.it2.pojo</groupId>
            <artifactId>springboot-enable-pojo</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
  1. 获取user
package com.it2.springbootenable.springbootenable01;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootEnable01Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext context=SpringApplication.run(SpringbootEnable01Application.class, args);
        Object obj=context.getBean("user");
        System.out.println(obj);
    }
}
  1. 运行项目。发现虽然引入了依赖,但是并没有创建user这个bean
    在这里插入图片描述
    j结论:
    通过例子说明,直接引入依赖,容器是不会初始化导入的Bean。

第二节、如何获取到user这个Bean

第一种、配置@ComponentScan

我们发现UserConfig和启动类并不是同一个包,UserConfig也不是启动类的子包。只有启动类同级或者子包才能被扫描到IOC容器中,所以我们需要手动配置包扫描,去扫描UserConfig,
在这里插入图片描述
在这里插入图片描述
给启动类添加注解

@ComponentScan("com.it2.pojo.springbootenablepojo.config")

在这里插入图片描述
再次运行,发现从IOC容器能获取到User
在这里插入图片描述

导入一个包,就要去配置包扫描,很繁琐。

第二种、配置@Import注解

通过@Import注解,导入UserConfig

@Import(UserConfig.class)

在这里插入图片描述
再次运行,同样可以获取到User。

在这里插入图片描述
通过@Import注解,我们需要事先知道UserConfig,这显的并不方便,如果有很多Config,意味着不仅要提前知道Config名称,还要配置一堆。

第三种、配置@Enable注解

在pojo模块种自定义一个EnableUser的注解

package com.it2.pojo.springbootenablepojo.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
 * 其实Enable注解就是将Import注解进行封装
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(UserConfig.class)
public @interface EnableUser {
}

在启动类添加@EnableUser注解
在这里插入图片描述
再次运行,同样可以获取到User
在这里插入图片描述
明显在使用@EnableUser时,只要添加注解即可,不需要进行复杂的配置,也不需要提前知道UserConfig。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值