-->
侧边栏壁纸
博主头像
断钩鱼 博主等级

行动起来,活在当下

  • 累计撰写 28 篇文章
  • 累计创建 34 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Spring @Enable模块装配

halt
2021-01-17 / 0 评论 / 1 点赞 / 1943 阅读 / 0 字

Enable模块装配的两种实现方式

1.基于注解的实现方式

  • Enable注解

@Import(HelloWordConfig.class) 直接导入具体配置类

/**
 * Enable模式注解
 *
 * @author mengshuo
 * @since 2021-01-16 09:32:58
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HelloWordConfig.class)
public @interface EnableHelloWord {
    /**
     * 系统用户名称
     *
     * @return 名称
     */
    String name() default "";
}
  • HelloWordConfig.java 配置类
/**
 * 普通配置类
 *
 * @author mengshuo
 * @since 2021-01-16 09:28:58
 */
public class HelloWordConfig implements Config {

    @Override
    public void helloWord() {
        System.out.println("helloWordEnabled");
    }
}
  • 启动类
/**
 * @author mengshuo
 * @since 2021-01-16 09:35:01
 */
@EnableHelloWord
public class EnableRun {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new SpringApplicationBuilder(EnableRun.class)
                        .web(WebApplicationType.NONE)
                        .run(args);
        Config bean = context.getBean(Config.class);
        bean.helloWord();
        context.close();
    }
}
  • 运行结果
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2021-01-17 11:49:26.708  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : Starting EnableRun on DESKTOP-4M5DVU4 with PID 5088 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:49:26.708  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : No active profile set, falling back to default profiles: default
2021-01-17 11:49:26.926  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : Started EnableRun in 0.671 seconds (JVM running for 1.337)
helloWordEnabled
与目标 VM 断开连接, 地址为: ''127.0.0.1:57684',传输: '套接字''

进程已结束,退出代码0

2.基于接口的实现方式

  • Enable注解

@Import(ConfigImportSelector.class) 导入 ImportSelector 实现类

/**
 * Enable模式注解
 *
 * @author mengshuo
 * @since 2021-01-16 09:32:58
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ConfigImportSelector.class)
public @interface EnableHelloWord {
    /**
     * 系统用户名称
     *
     * @return 名称
     */
    String name() default "";
}
  • ImportSelector 实现类

用来根据不同的信息实现来返回不同类型的配置

/**
 * selector类
 *
 * @author mengshuo
 * @since 2021-01-16 09:55:41
 */
public class ConfigImportSelector implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata metadata) {

        Map<String, Object> attributes = metadata.getAnnotationAttributes(EnableHelloWord.class.getName());
        if (System.getProperty("user.name").equals(attributes.get("name"))) {
            return new String[]{AdminConfig.class.getName()};
        } else {
            return new String[]{HelloWordConfig.class.getName()};
        }
        
    }
}
  • 配置类

一个配置类接口 一个管理员配置类 一个普通的配置类 通过 ConfigImportSelector 进行判断返回那个类作为配置类使用

/**
 * 配置类接口
 *
 * @author mengshuo
 * @since 2021-01-16 10:17:04
 */
public interface Config {
    /***
     * helloWord
     */
    default void helloWord() {
    }
}

/**
 * 管理员配置
 *
 * @author mengshuo
 * @since 2021-01-16 10:09:59
 */
public class AdminConfig implements Config {

    @Override
    public void helloWord() {
        System.out.println("启用管理类Config");
    }
}

/**
 * 普通配置类
 *
 * @author mengshuo
 * @since 2021-01-16 09:28:58
 */
public class HelloWordConfig implements Config {

    @Override
    public void helloWord() {
        System.out.println("helloWordEnabled");
    }
}
  • 启动类稍作修改

65722 为我电脑的 user.name

/**
 * @author mengshuo
 * @since 2021-01-16 09:35:01
 */
@EnableHelloWord(name = "65722")
public class EnableRun {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new SpringApplicationBuilder(EnableRun.class)
                        .web(WebApplicationType.NONE)
                        .run(args);
        Config bean = context.getBean(Config.class);
        bean.helloWord();
        context.close();
    }
}
  • 运行检验结果

    • 使用name值为65722结果
已连接到目标 VM, 地址: ''127.0.0.1:57696',传输: '套接字''

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2021-01-17 11:50:54.895  INFO 13460 --- [           main] com.example.demo.enabled.EnableRun       : Starting EnableRun on DESKTOP-4M5DVU4 with PID 13460 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:50:54.910  INFO 13460 --- [           main] com.example.demo.enabled.EnableRun       : No active profile set, falling back to default profiles: default
2021-01-17 11:50:55.082  INFO 13460 --- [           main] com.example.demo.enabled.EnableRun       : Started EnableRun in 0.635 seconds (JVM running for 1.293)
启用管理类Config
与目标 VM 断开连接, 地址为: ''127.0.0.1:57696',传输: '套接字''

进程已结束,退出代码0

- 不添加name值 或者 填写其他值
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)

2021-01-17 11:49:26.708  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : Starting EnableRun on DESKTOP-4M5DVU4 with PID 5088 (E:\WorkSpace\demo\target\classes started by 65722 in E:\WorkSpace\demo)
2021-01-17 11:49:26.708  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : No active profile set, falling back to default profiles: default
2021-01-17 11:49:26.926  INFO 5088 --- [           main] com.example.demo.enabled.EnableRun       : Started EnableRun in 0.671 seconds (JVM running for 1.337)
helloWordEnabled
与目标 VM 断开连接, 地址为: ''127.0.0.1:57684',传输: '套接字''

进程已结束,退出代码0

总结

  • 基于注解的方式实现比较简单 但是可扩展性就比较差 当同一种功能有多种实现方式时就不再适用

  • 基于接口的实现方式则更加灵活 可以根据不同的需要返回不同的实现

1
博主关闭了所有页面的评论