gpt4 book ai didi

java - 如何将 application.properties 中的值分配给 @Qualifier

转载 作者:行者123 更新时间:2023-11-30 02:02:38 25 4
gpt4 key购买 nike

我想使用 application.properties tu |@Qualifier 中的 @Service 名称分配一个值。我尝试过,但没有成功。

事实上,我有两个实现相同接口(interface)的服务,我想从 application.properties 更改服务

有人知道如何做到这一点吗?

这是我的代码

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
public class Controler {


@Qualifier("${service.name}")
@Autowired
private InterfaceTest interfaceTest;


@GetMapping("/test")
public String test(){
return interfaceTest.test();
}
}

非常感谢您的帮助

最佳答案

我认为您可以通过使用 EnvironmentApplicationContext bean 在此 Controller 的构造函数中执行此操作。

只需从字段中删除 Autowired 注释,并通过构造函数接受其他参数。

public Controller(Environment environment, ApplicationContext applicationContext) {
String serviceName = environment.getProperty("service.name");
this.interfaceTest = applicationContext.getBean(serviceName, InterfaceTest.class);
}

据我所知,除了文字之外,Spring 的那些 bean 限定符和其他注释。

希望这有帮助。

关于java - 如何将 application.properties 中的值分配给 @Qualifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52337740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com