首页 > 解决方案 > 如何将 application.properties 中的 aa 值分配给 @Qualifier

问题描述

我想用 application.properties tu |@Qualifier 中的 @Service 名称分配一个值。我试过了,但它不起作用。

事实上,我有两个实现相同接口的服务,我想从 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();
    }
}

非常感谢您的帮助

标签: javaspringspring-boot

解决方案


我认为你可以在这个控制器的构造函数中通过使用EnvironmentApplicationContextbean 来做到这一点。

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

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

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

希望这可以帮助。


推荐阅读