簡體   English   中英

春季:@Service類,其構造函數帶有@Autowired(required = false)參數:如何使用這些參數初始化它?

[英]Spring: @Service class with constructor with @Autowired(required = false) parameters: how to initialize it with these parameters?

我有一個服務類,我想使用構造函數參數的不同傳入值進行動態初始化:

@Service
public class SomeServiceImpl implements SomeService {

    private final SomeProperties someProperties;
    private final String url;
    private final String password;

    private final Logger log = LoggerFactory.getLogger(SomeServiceImpl.class);

    @Autowired
    public SomeServiceImpl(SomeProperties someProperties,
                             @Autowired(required = false) String url,
                             @Autowired(required = false) String password) {
        this.someProperties = someProperties;
        this.url = url;
        this.password = password;
    }

是否可以在運行時通過使用自己提供的@Autowired(required = false)參數(在這種情況下為自己的url和密碼)在另一個spring組件類中初始化此@Service 這段代碼看起來如何?

你可以這樣

@Configuration
class SomeConfigClass {


    @Autowired
    SomeProperties someProperties

    @Value("${url1}")
    String url1

    @Value("${password1}")
    String password1

    ..............
     // Do this for other url's and properties or check out @ConfigurationProperties
    ..............

    @Bean("someService1")
    public SomeService() {
        return new SomeService(someProperties, url1, password1);
    }


    @Bean("someService2")
    public SomeService() {
        return new SomeService(someProperties, url2, password2);
    }

    ...............

    ..............
}

創建工廠類

@Configuration //typo corrected
class SomeServiceFactory {

  @Autowired // Spring will Autowire all instances of SomeService with bean name as key
  Map<String, SomeService> someServiceMap;

  public SomeService getSomeServiceByName(String name) {
    return someServiceMap.get(name);
  }
}

然后您可以使用這樣的實例

@RestController
class SomeController {

    @Autowired
    SomeServiceFactory someServiceFactory;


    public void someEndpoint() {
     SomeService someService1 = SomeServiceFactory.getSomeServiceByName("someService1"); //You need to decide what argument to pass based on condition
     someService1.someFunction(...); // this will have url1 and password1
   } 
}

用戶名和密碼來自哪里? 也許您可以簡單地從構造函數中刪除它們,並使用@Value批注從屬性文件中讀取值?

@Service
public class SomeServiceImpl implements SomeService {

    private final SomeProperties someProperties;

    @Value("${service.url}")
    private String url;

    @Value("${service.password}")
    private String password;

    private final Logger log = LoggerFactory.getLogger(SomeServiceImpl.class);

    @Autowired
    public SomeServiceImpl(SomeProperties someProperties) {
        this.someProperties = someProperties;
    }

暫無
暫無

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

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