Spring有哪些注入方式呢?
下文笔者讲述Spring注入方式分享,如下所示
Spring中有以下注入方式: 1.setter属性注入 2.构造方法注入 3.lombok注入例:
1.setter属性注入
@Controller public class HelloController { private TestService testService; private UserService userService; @Autowired public void setAlphaService(TestService testService) { this.alphaService = alphaService; } @Autowired public void setBetaService(UserService userService) { this.betaService = betaService; } }
2.构造方法注入
普通实现方法 @Controller public class HelloController { private final TestService testService; private final UserService userService; @Autowired public HelloController(TestService testService, UserService userService) { this.testService = testService; this.userService = userService; } }
3.lombok注解方式
@AllArgsConstructor @Controller public class HelloController { private final TestService testService; private final UserService userService;a }
目前我们最常用的注解方式为:注解注入
注解方式注入 @Controller public class HelloController { @Autowired private TestService testService; @Autowired private UserService userService; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。