From 859ba987ec292abd08ab7c1d23599d829b18b424 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Sat, 19 Sep 2026 16:21:15 +0800 Subject: [PATCH] =?UTF-8?q?javaEEday05-=E5=88=86=E5=B1=82=E8=A7=A3?= =?UTF-8?q?=E8=80=A6-IOC&DI-DI=E8=AF=A6=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/inmind/controller/EmpController.java | 4 ++++ .../main/java/com/inmind/service/impl/EmpServiceImplA.java | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/springboot-web-req-resp/src/main/java/com/inmind/controller/EmpController.java b/springboot-web-req-resp/src/main/java/com/inmind/controller/EmpController.java index 7e73178..5878a0b 100644 --- a/springboot-web-req-resp/src/main/java/com/inmind/controller/EmpController.java +++ b/springboot-web-req-resp/src/main/java/com/inmind/controller/EmpController.java @@ -5,7 +5,9 @@ import com.inmind.pojo.Result; import com.inmind.service.EmpService; import com.inmind.service.impl.EmpServiceImplA; import com.inmind.utils.XmlParserUtils; +import jakarta.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -15,6 +17,8 @@ import java.util.List; public class EmpController { //设置一个员工业务对象 @Autowired//运行时,IOC容器会提供该类型的bean对象,并赋值给该变量----依赖注入 + @Qualifier("empServiceImplA") //优先级更高,比@Primary,优先级高 + //@Resource(name = "empServiceImplB")//jdk提供的注解,不用 private EmpService empService ; @RequestMapping("/listEmp") diff --git a/springboot-web-req-resp/src/main/java/com/inmind/service/impl/EmpServiceImplA.java b/springboot-web-req-resp/src/main/java/com/inmind/service/impl/EmpServiceImplA.java index 2e14be2..441bb89 100644 --- a/springboot-web-req-resp/src/main/java/com/inmind/service/impl/EmpServiceImplA.java +++ b/springboot-web-req-resp/src/main/java/com/inmind/service/impl/EmpServiceImplA.java @@ -4,10 +4,13 @@ import com.inmind.dao.EmpDao; import com.inmind.pojo.Emp; import com.inmind.service.EmpService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import java.util.List; - -//@Component //将当前类交给IOC容器管理,让它称为IOC容器中的bean对象---IOC控制反转 +@Primary //当DI依赖注入EmpService的变量时,优先使用当前实现类 +@Service //将当前类交给IOC容器管理,让它称为IOC容器中的bean对象---IOC控制反转 public class EmpServiceImplA implements EmpService { //设置一个dao的成员变量 @Autowired//运行时,IOC容器会提供该类型的bean对象,并赋值给该变量----依赖注入