@Autowired注入其他模块的bean失败

17 篇文章 0 订阅
9 篇文章 0 订阅

一、在Spring Boot中,如果要自动扫描和创建bean,需要在应用的启动类上使用@ComponentScan注解来指定要扫描的包。确保你已经将GlobalConfig类所在的包和父包都添加到了@ComponentScan注解的value属性中。 例如,如果GlobalConfig类所在的包为com.demo.config,则可以使用以下方式来扫描整个包路径及其子包:

@SpringBootApplication
@ComponentScan(basePackages = "com.demo")
public class MyApp {
   public static void main(String[] args) {
      SpringApplication.run(MyApp.class, args);
   }
}

确保上述代码中的com.demo是你的包路径的根路径。如果com.demo.config是在com.demo包路径下的一个子包,那么它也应该被正确扫描到。 另外,请检查是否有其他方式明确定义了GlobalConfig的bean,如在XML配置文件中使用元素定义了该bean。如果有,请将其移除,并使用@ComponentScan注解来自动扫描bean。

二、使用applicationContext.xml文件配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.demo"/>
    <bean id="globalConfig" class="com.demo.common.config.GlobalConfig">
    <!--${platform.name}获取yml配置文件中platform的name的值-->
        <property name="name" value="${platform.name}"/>
        <property name="version" value="${platform.version}"/>
        <property name="copyrightYear" value="${platform.copyrightYear}"/>
        <property name="profile" value="${platform.profile}"/>
    </bean>
</beans>

然后使applicationContext.xml生效
在启动类上添加注解

@ImportResource("applicationContext.xml")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值