简体   繁体   中英

Spring autowiring bean with mixed constructor

I have two beans like this:

@Component
@Scope("prototype")
class A {
    A(int number, B anotherBean) {
         //...
    }
}

@Component
class B {
     //..
}

How can I build A and have B autowired? If I use new I won't get anotherBean's value, if I use autowiring I won't get number's value.

Edit: The number is calculated at runtime, so I can't use @Value like answers suggested.

Make use of @Value and inject the number's value via property. Your ClassA should look something like

@Component
@Scope("prototype")
class A {

    @Autowired
    A(@Value("${some.property}")int number, B anotherBean) {
       //...
    }
}

Edit (post additional condition of runtime value for number)

You can fetch the bean from BeanFactory.getBeans method as correctly pointed out by M.Deinum in comments.

I found this question today looking for an answer myself. After some consideration, here's a solution I think I'm going with. Basically I'm baking the factory method into the bean's class. This has the advantage of keeping the 'internal' dependencies (B in this example) all inside the 'A' class, and hidden from the caller, while still allowing prototype creation using a caller's runtime value. And it doesn't require yet another class file just for a factory method.

public class A {

  private A (int number, B otherBean) {
  ...
  }

  @Configuration
  public static class BeanConfig {

    @Autowired
    private B otherBean;

    @Bean
    @Scope("prototype")
    public A makeA(int number) {
      return new A(number, otherBean);
    }
  }
}

Then you can request a prototype bean instance while providing only the runtime value:

applicationContext.getBean(A.class, 1);

You need to annotate the desired constructor-to-be-used as @Autowired, among other ways you can find with a Google search. As for your issue with 'number', there are ways to use annotations to set parameter values as well, also not difficult to find with a Google search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM