java—spring boot中@qualifier的替代方法

6psbrbz9  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(463)

我有这个场景
a组正在实施 interface Vehicle 作为 ClassAVehicle 团队b正在实现一个 Jmeter 板服务,其中它使用车辆实现
现在a组有了一个新的车辆实现为classbvehicle。b队想用它。我知道的一个方法是使用@qualifier注解。但为此,我需要更改b组的代码。所以我这里有紧耦合吗?我可以有一些基于xml的配置,以便团队b的代码自动解析新的classbvehicle示例吗?

interface Vehicle{
    int getNoTyre();
}
class ClassAVehicle{
    int getNoTyre(){
        return 1;
    }
}
class ClassBVehicle{
    int getNoTyre(){
        return 2;
    }
}
class Dashboard{
    // Here everything is fine until classBVehicle is not there
    // Now I want to use new classBVehicle.
    // One way I see is that using @Qualifier but will it not be tight coupling? 
    @Autowired
    Vehicle oldAInstance;
}
vuktfyat

vuktfyat1#

如果您使用xml来定义bean,那么您的去耦方法是很好的。另一种方法是,可以使用applicationcontext在注解程序中动态获取bean。有两种方法可以通过beanname或beanclass获得bean。以下是示例:

@Service
public class BService {

    private Vehicle vo;

    @Autowired
    ApplicationContext context;

    public void getVehicle(String beanName){
        this.vo =  (Vehicle) context.getBean(beanName);
    }

    public void getVehicle(Class beanClz){
        this.vo = (Vehicle) context.getBean(beanClz);
    }

    public void print(){
        System.out.println("---class is "+vo.getClass());
    }

}

public interface Vehicle  {
}

@Component
public class OneVehicle implements Vehicle{
}

@Component
public class TwoVehicle implements Vehicle{
}

@SpringBootApplication
public class SpringDependenciesExampleApplication implements ApplicationRunner {

    @Autowired
    BService bService;

    public static void main(String[] args) {
        SpringApplication.run(SpringDependenciesExampleApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        bService.getVehicle("oneVehicle");
        bService.print();
    }
}

// output is ---class is class OneVehicle

相关问题