java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Lombok spring 注入

如何使用Lombok进行spring 注入

作者:Brilliant Nemo

本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效率,感兴趣的朋友一起看看吧

Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter注入

使用 Lombok 进行setter注入(尽量优先使用setter注入)

@Service
@Setter(onMethod_ = {@Autowired})
public class TestServiceImpl implements TestService {
    private TestDao testDao;
}

看一下编译的内容

@Service
public class TestServiceImpl implements TestService {
    private TestDao testDao;
    @Autowired
    public void setTestDao(final TestDao testDao) {
        this.testDao= testDao;
    }
}

使用 Lombok 进行构造器注入

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TestServiceImpl implements TestService {
    private final TestDao testDao;
}

 或

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TestServiceImpl implements TestService {
    @lombok.NonNull
    private TestDao testDao;
}

编译的内容

@Service
public class TestServiceImpl implements TestService {
    private TestDao testDao;
    @Autowired
    public void TestServiceImpl(final TestDao testDao) {
        this.testDao= testDao;
    }
}

到此这篇关于优雅的使用Lombok进行spring 注入的文章就介绍到这了,更多相关Lombok spring 注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文