Spring启动报错问题之注解@RequiredArgsConstructor
Spring启动报错问题之注解@RequiredArgsConstructor。
·
Spring启动报错问题之注解@RequiredArgsConstructor
关于类添加注解@RequiredArgsConstructor 导致@Autowired注入找不到实例问题
报错:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'studentServiceImpl' defined in file [D:\Desktop\2021-0125\syh-
test\target\classes\com\service\student\StudentServiceImpl.class]: Unsatisfied dependency
expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'workServiceImpl': Unsatisfied dependency expressed through field 'service'; nested exception
is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean
with name 'studentServiceImpl': Requested bean is currently in creation: Is there an
unresolvable circular reference?
创建WorkService 是注入的StudentService无法找到实例
@RequiredArgsConstructor注解导致
service–StudentService
package com.service.student;
/**
* @author syh
* @date 2023/7/19 11:07
* 描述
*/
public interface StudentService {
void test();
}
package com.service.student;
import com.service.play.PlayService;
import com.service.work.WorkService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author syh
* @date 2023/7/19 11:08
* 描述
*/
@Service
@RequiredArgsConstructor
//@RequiredArgsConstructor(onConstructor_ = {@Lazy}) 此方法可解决无法注入问题
public class StudentServiceImpl implements StudentService {
//因为这样会变成成员变量导致空参构造消失注入失败(可以new一下试试)
//使用AutoWirte 则不会记录为变量 仍然为空参构造
private final WorkService workService;
@Override
public void test() {
}
}
service–WorkService
/**
* @ author:syh
* date:2023/7/19 11:09
* 描述:
**/
public interface WorkService {
}
package com.service.work;
import com.service.student.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author syh
* @date 2023/7/19 11:09
* 描述
*/
@Service
public class WorkServiceImpl implements WorkService {
@Autowired
//@Lazy 加上这个注解就不会有注入问题,最后Spring会创建StudentService实例,使用不受影响
StudentService service;
}
解决方案:
1.不使用@RequiredArgsConstructor 注解,使用@AutoWirte 注入使用
2.在注入的StudentService 加上懒加载
3.@RequiredArgsConstructor(onConstructor_ = {@Lazy})
更多推荐
已为社区贡献1条内容
所有评论(0)