簡體   English   中英

XML 定義的 spring bean 的程序等價物是什么

[英]What is the programatic equivalent of a XML defined spring bean

在 xml 中定義這樣的 bean 的程序等效項是什么:

<bean id="foo" class="com.bizz.Foo" />

理想情況下,我希望能夠讓 spring 創建那個 bean,而不使用 XML 並且不調用new並且為了在@Configuration類型 class 中發生這種情況。例如:

@Configuration
public ConfigBar {
  @Bean
  public com.bizz.Foo foo() {
    return /* Programmatic equivalent of <bean id="foo" class="com.bizz.Foo" /> here*/; 
  }
}

我不認為new Foo()是等價的:

  • 因為 spring 能夠選擇要使用的構造函數,它可能不是無參數構造函數。
  • spring 能夠注入依賴項,我認為這不會在這里完成。

我知道 spring 正在做一些反思來實現這一點,但簡單地說這不是這個問題的答案。

那么我們如何讓 spring 以編程方式創建Foo bean,讓 spring 注入依賴項、選擇構造函數以及 spring 在 XML 中定義時通常會執行的其他任務?

等效項是@Component或其任何變體,例如@Controller@Service 只要你的bean在package包含在組件掃描Spring中,就能在運行時找到你的bean並將它注入到其他bean中。

舉個例子:

@Component
public class Foo {
    //...
}

@Service
public class Bar {

    // Spring will find and inject Foo bean creating it if necessary when 
    // creating the Bar "service" bean 
    @Autowired
    private Foo foo;

    //...
}

我已經解決了:

@Bean
@Autowired
public Foo foo(AutowireCapableBeanFactory autowireCapableBeanFactory) {
    return autowireCapableBeanFactory.createBean(Foo.class);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM