【Java】DI依赖注入详解

DI注入时有以下几种方式 

1、属性注入:@Autowired注解

通过@Autowired直接进行属性注入

@Service
public class UserService {public void sayHi(){System.out.println("Hi,service");}
}
@Controller
public class UserController {@Autowiredprivate UserService userService;public void sayHi(){System.out.println("Hi,controller");userService.sayHi();}
}
@SpringBootApplication
public class IocSpringApplication {public static void main(String[] args) {ApplicationContext context = SpringApplication.run(IocSpringApplication.class, args);UserController controller = context.getBean(UserController.class);controller.sayHi();}}

结果显示如下

注意📢

⭐@Autowired会先根据名称来获取,如果获取到了,正确响应

⭐如果没有获取到,就根据类型匹配,此时,如果匹配到多个,报错 

2、构造方法注入

@Controller
public class UserController {private UserService userService;private UserComponent userComponent;public UserController(){}public UserController(UserService userService){this.userService = userService;}@Autowiredpublic UserController(UserService userService, UserComponent userComponent){this.userService = userService;this.userComponent = userComponent;}public void sayHi(){System.out.println("Hi,controller");userService.sayHi();userComponent.sayHi();}
}

构造方法注入时要注意📢

✅(1)一定要写无参构造方法,否则会报错

✅(2)如果不使用@Autowired注解,那么几个构造方法中默认使用无参构造方法

✅(3)所以在要使用的构造方法上要叫上@Autowired,属性才被注入 

3、Setter方法注入

@Controller
public class UserController {private UserService userService;@Autowiredpublic void setUserService(UserService userService) {this.userService = userService;}public void sayHi(){System.out.println("Hi,controller");userService.sayHi();}
}

Setter方法上也要使用@Autowired注解

4、三种方法的对比

@Autowired属性注入构造方法注入Setter方法注入
适用范围只能用于 IoC 容器,如果是非 IoC 容器不可用,并且只有在使用的时候才会出现 NPE(空指针异常)通用性好,构造方法是JDK支持的,所以更换任何框架都是适用的--
能否注入被被final修饰的变量不能不能
注入对象会不会被修改--不会会。注入对象可能会被改变,因为setter方法可能会被多次调用,就有被修改的风险