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
@RequireArgsConstructor(onConstructor_ ={@Autowired})
public class TestServiceImpl implements TestService {
private final TestDao testDao;
}
或
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autwired})
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;
}
}