Java教程

Spring 注入方式

本文主要是介绍Spring 注入方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、setter 属性注入

@Controller
public class HelloController {
    private AlphaService alphaService;
    private BetaService betaService;
    
    @Autowired
    public void setAlphaService(AlphaService alphaService) {
        this.alphaService = alphaService;
    }
    @Autowired
    public void setBetaService(BetaService betaService) {
        this.betaService = betaService;
    }
}

2、构造方法注入

普通实现方法

@Controller
public class HelloController {
    private final AlphaService alphaService;
    private final BetaService betaService;
    
    @Autowired
    public HelloController(AlphaService alphaService, BetaService betaService) {
        this.alphaService = alphaService;
        this.betaService = betaService;
    }
}

 lombok注解方式

@AllArgsConstructor
@Controller
public class HelloController {
    private final AlphaService alphaService;
    private final BetaService betaService;
    

}

 3、注解方式注入-目前最常用

@Controller
public class HelloController {
    @Autowired
    private AlphaService alphaService;
    @Autowired
    private BetaService betaService;
}

这篇关于Spring 注入方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!