• springboot-enable

    @SpringBootApplication
    public class SpringbootEnableApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringbootEnableApplication.class, args);
            // 获取 Bean
            Object user = context.getBean("user");
            System.out.println(user);
        }
    }
    
  • springboot-enable-other

    // domain.User
    public class User {}
    
    // config.UserConfig
    @Configuration
    public class UserConfig {
        @Bean
        public User user() {
            return new User();
        }
    }
    

然后在 springboot-enable 的 pom.xml 中加入,

<dependency>
	<groupId>com.casey</groupId>
	<artifactId>springboot-enable-other</artifactId>
</dependency>

运行 springboot-enable 项目,发现报错找不到 user 这个 bean。

⚠️ 问题出在 @SpringBootApplication 中的 @ComponentScan

​ @ComponentScan 扫描范围:当前引导类所在包及其子包。

解决方案

参考 黑马程序员SpringBoot教程
在启动类加入 @ComponentScan("com.casey"),则报错:Redundant declaration: @SpringBootApplication already applies given @ComponentScan.

原来,@SpringBootApplication 中已经包含了 @ComponentScan 的功能,所以在启动类上再次显式声明 @ComponentScan 是多余的。
于是改用,

@SpringBootApplication(scanBasePackages = "com.casey")

解决了 Redundant declaration 的错误。
但是依然报错:NoSuchBeanDefinitionException: No bean named ‘user’ available。

猜测是坐标依赖没写对,加入了版本号,

<dependency>
	<groupId>com.casey</groupId>
	<artifactId>springboot-enable-other</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</dependency>

成功启动了!
后来发现,

@SpringBootApplication//(scanBasePackages = "com.casey")
@ComponentScan("com.casey.config")

也是能跑的。必须引入模块的版本号。

0.0.1-SNAPSHOT 是 Maven 的一个特殊版本标识符,通常用于表示正在开发中的项目的版本。在 Maven 中,SNAPSHOT 版本表示一个不稳定的、可能随时更新的版本,通常用于开发和测试阶段。当使用 SNAPSHOT 版本时,Maven 会尝试从仓库中获取最新的快照版本。

Logo

鸿蒙生态一站式服务平台。

更多推荐