Spring有哪些注入方式呢?

乔欣 Spring 发布时间:2022-11-21 21:54:29 阅读数:5295 1
下文笔者讲述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;
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202211/4958.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者