spring bean一个接口有多个实现类该怎么处理

定义接口

public interface HelloWorldService{
	String doSth();
}

实现类

@Slf4j
@Service("HelloWorld01Service")
public class HelloWorld01ServiceImpl implements HelloWorldService{
	@Override
	public String doSth(){
		log.info("hello world 01 service");
		return "hello01";
	}
}

@Slf4j
@Service("HelloWorld02Service")
public class HelloWorld02ServiceImpl implements HelloWorldService{
	@Override
	public String doSth(){
		log.info("hello world 02 service");
		return "hello02";
	}
}

调用实现类

import org.springframework.beans.factory.annotation.Qualifier;

@RestController
@RequestMapping("/hello-world")
public class HelloWorldController{
	@Autowired
	@Qualifier("HelloWorld01Service")
	private HelloWorldService helloWorld01Service;

	@Autowired
	@Qualifier("HelloWorld02Service")
	private HelloWorldService helloWorld02Service;

	@GetMapping("/hello01")
	public String hello01(){
		return this.helloWorld01Service.doSth();
	}
	@GetMapping("/hello02")
	public String hello02(){
		return this.helloWorld02Service.doSth();
	}
}
可以的,Spring框架提供了一种叫做"依赖注入"(Dependency Injection)的机制,可以通过配置文件或者注解的方式来实现接口多个实现类之间的切换。具体实现方式有以下两种: 1. 通过配置文件实现多个实现类之间的切换。在Spring的配置文件中,可以使用<bean>元素来配置类的实例,其中可以指定bean的id和class属性,同时也可以使用<qualifier>元素来指定该bean在多个实现类中的具体实现。 举个例子,假设我们有一个接口UserService,有两个实现类UserServiceImpl和UserServiceImpl2。那么可以这样配置: ``` <bean id="userService1" class="com.example.service.impl.UserServiceImpl"/> <bean id="userService2" class="com.example.service.impl.UserServiceImpl2"/> <bean id="userService" class="com.example.service.UserService"> <qualifier value="userService1"/> </bean> ``` 这样,我们就可以在需要使用UserService的地方,通过注入userService来获取具体的实现类。 2. 通过注解实现多个实现类之间的切换。在接口上使用@Qualifier注解来指定具体的实现类,同时在实现类上使用@Primary注解来指定默认的实现类。 举个例子,假设我们有一个接口UserService,有两个实现类UserServiceImpl和UserServiceImpl2。那么可以这样配置: ``` public interface UserService { void doSomething(); } @Service @Qualifier("userService1") public class UserServiceImpl implements UserService { @Override public void doSomething() { System.out.println("UserServiceImpl do something"); } } @Service @Qualifier("userService2") public class UserServiceImpl2 implements UserService { @Override public void doSomething() { System.out.println("UserServiceImpl2 do something"); } } @Component public class UserController { @Autowired @Qualifier("userService1") private UserService userService; public void test() { userService.doSomething(); } } ``` 在UserController中,我们通过@Autowired注解将userService注入进来,同时使用@Qualifier注解来指定具体的实现类。这样,我们就可以在需要使用UserService的地方,通过注入具体的实现类来获取不同的实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值