簡體   English   中英

如何避免在Java Bean中使用Spring注釋,而僅在配置類中使用它們?

[英]How to avoid the use of Spring annotations in my java beans and use them only in the configuration class?

我是Spring的新手,這是我的第一篇文章,我開始使用spring注釋,我能夠使用XML配置來配置我的項目,現在我可以僅使用注釋並避免使用XML來配置它。

但是我目前的需要是避免在Java類(beans)中使用批注,而僅在用於配置Spring的AppConfig.java類中使用它。

這是我當前的工作配置:

AppConfig.java

@Configuration
@ComponentScan(basePackageClasses= {BlocBuilder.class,... all my classes go here})
public class AppConfig {


  @Bean
  @Scope("prototype")
  public BlocBuilder blocBuilder(){ 
      return new BlocBuilder();
  }

}

這是我的Java類之一。

BlocBuilder.java

public class BlocBuilder {

@Autowired
@Qualifier("acServices")
private SomeInterface someInterface;

public SomeInterface getSomeInterface() {
    return someInterface;
}
public void setSomeInterface(SomeInterface someInterface) {
    this.someInterface = someInterface;
}

我想要實現的是避免在類中使用注釋,例如在BlocBuilder.java類中,我不想使用注釋並將它們移到config類。

我該如何管理?

任何幫助,我們將不勝感激。

您正在尋找構造函數注入。 BlocBuilder創建一個1-arg構造函數,該構造函數SomeInterface類型參數。 然后在config類中,將其作為參數傳遞:

@Configuration
@ComponentScan(basePackageClasses= {BlocBuilder.class,... all my classes go here})
public class AppConfig {

  @Bean
  public SomeInterface someInterface() {
      return new SomeInterfaceImpl();
  }

  @Bean
  @Scope("prototype")
  public BlocBuilder blocBuilder(){ 
      return new BlocBuilder(someInterface());
  }
}

我不推薦配置類。 它將所有豆類結合在一起。

Spring配置不必是全部或全部:注釋或XML。 您可以選擇混合和搭配。 將注釋放在所需的類中,其余使用XML。

暫無
暫無

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

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