【问题标题】:Spring inject a bean into another beanSpring将一个bean注入另一个bean
【发布时间】:2019-08-12 14:32:12
【问题描述】:

我正在尝试将一个 bean 注入另一个使用它的 bean。我该怎么做?

public class MySpringConfig{
@Bean
public MyObject getMyObject() {
  //.....

  return MyObjectInstance;
}



@Bean
public SomeObject getSomeObject(MyObject myObject) {

  //.....

  return SomeObjectInstance;
 }    
}

【问题讨论】:

  • 你真的尝试过这段代码吗?这不行吗?
  • 您可以尝试将 {@Autowire} 注释添加到注入您的 bean 的 getSomeObject 方法参数
  • 正如@lealceldeiro 指出的那样,如果满足某些约束,您的代码应该可以工作。如果它不起作用,您应该将参数对象命名为与您需要的 @Bean 方法相同,在您的情况下,它应该是 getSomeObject(MyObject getMyObject)

标签: java spring dependency-injection


【解决方案1】:

我认为您可以通过这种方式做到这一点,这在我的项目中有效。

@Configuration
public class AppConfig {

 @Bean
 public Bean1 foo(@Qualifier("bean2") Bean2 bean2) {
  return new Bean1(bean2);
 }

}

【讨论】:

  • 如果我们要手动调用它要传递什么?例如 AppConfig appConfig=new AppConfig(); Bean1 myBean=appConfig.foo();//我们在这里作为Param传递什么?并且每次执行 appConfig.foo() 时我都想获得相同的对象?
【解决方案2】:

我认为这可能有效!

 @Configuration
 public class AppConfig {

  @Bean
  public Bean2 bean2() {
      return new Bean2();
  }

  @Bean
  @DependsOn({"bean2"})
  public Bean1 foo(@Autowired Bean2 bean2) {
     return new Bean1(bean2); // or your can write new Bean1(bean2());
  }

}

【讨论】:

  • @DependsOn@Autowired 不需要。
【解决方案3】:

参数在@Bean@Component 中的工作方式并不完全相同。
对于使用@Component 注释的类,自动装配构造函数需要指定它们,但在@Bean 声明中,您不需要提供参数来指定要使用的MyObject 依赖项(虽然它会起作用)如果那样的话可以在当前类中访问,这是您的情况。
所以你想通过在@Bean 定义中调用getMyObject() 来直接注入bean。
例如传递一个构造函数 arg :

@Bean
public SomeObject getSomeObject() {

  //....
  // you injected MyObject in the current bean to create
  SomeObject object = new SomeObject(getMyObject());
  //...
  return SomeObjectInstance;     
}

并且不要忘记使用@Configuration 注释该类以使其被Spring 考虑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2014-01-24
    • 2011-12-28
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多