【问题标题】:Spring Boot Autowired failed - nullSpring Boot Autowired 失败 - null
【发布时间】:2016-10-11 04:47:42
【问题描述】:

我有 3 个类,它们位于 Spring Boot 应用程序的不同包中,如下所示: 为什么@Autowired 只在某些类中工作?我做错了什么吗?

@Configuration
public class Configurations{
   @Autowired
   Prop prop;  //works fine

   @Bean
   //other bean definitions

}

@Component
public class Prop{
   public void method(){};
}

public class User{
   @Autowired
   Prop prop;  //does not work, null

   public void doWork(){
      prop.method();
   }

}

我也尝试过@PostConstruct,但结果相同

public class User{
       @Autowired
       Prop prop;  //does not work, null

       @PostConstruct
       public void doWork(){
          prop.method();
       }

    }

【问题讨论】:

  • 将组件注解更改为bean注解之后,您可以使用bean注解并在配置中创建一个方法,然后您可以在其他方法上使用bean public Prop prop(){...}

标签: spring-boot autowired


【解决方案1】:

@Autowired 注释仅在 Spring 检测到类本身应该是 Spring bean 时才有效。

在您的第一个示例中,您使用 @Configuration 注释注释了 Configurations。另一方面,您的 User 类没有表明它应该是 Spring bean 的注释。

有各种注释(具有不同的含义)可以使您的类被 Spring 容器拾取,例如@Service@Component@Controller@Configuration、...。但是,这仅在您的类位于 Spring 容器正在扫描的包中时才有效。使用 Spring boot,保证这一点的最简单方法是将您的 User 类放入主类(使用 @SpringBootApplication 注释的类)的(子)包中。

您也可以通过在Configurations 中编写以下方法来手动创建 bean:

@Bean
public User user() {
    return new User();
}

在这种情况下,您不必注释您的 User 类,也不必确保它位于正在扫描的包中。

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 2015-06-30
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多