小马哥这块讲的有点小瑕疵,应该把@Configuration去掉。用@Configuration的话 让人误解是使用了@Companetscan

来源:2-4 Spring Framework 手动装配 - @Enable 基于注解驱动方式

我爱吻篮板

2020-12-13

public class HelloWorldConfig {

    public String helloWorld(){
        return "hello world by Enabled annoation";
    }
}

运行代码

@EnableHelloWorld
public class HelloWorldEnable {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =new SpringApplicationBuilder(HelloWorldEnable.class)
                .web(WebApplicationType.NONE)
                .run(args);



        HelloWorldConfig helloWorldConfig=context.getBean(HelloWorldConfig.class);

        // 请注意 这里获取到的HelloWorldConfig 可是没有通过任何注解来完成注册的
        // 比如@Confituration @Bean.... 这类注解一概没有使用
        System.out.printf("获取到helloWorldConfig的内容为:"+helloWorldConfig.helloWorld());


    }
}
写回答

1回答

独孤天子

2021-09-01

老师主要讲的是通过@Import导入配置类从而注册多个bean,配置类的实现方式可以是@Configuration注解,可以是 ImportSelector接口实现,可以是ImportBeanDefinitionRegistrar接口实现。  而不仅仅是为了说明 @Import可以导入一个bean,如果只是为了一个bean,何必用import。参见 

ConfigurationClassParser.processImports
0
0

Spring Boot2.0深度实践 核心原理拆解+源码分析

系统化剖析Spring Boot 2.0,掌握技术原理,学习源码阅读技巧

2904 学习 · 213 问题

查看课程