Spring Boot中的循环依赖

时间:2017-04-30 12:20:28

标签: java spring-boot

我正在尝试在我的bootspring项目中使用restTemplate,当我编译时给出了这样的错误:

There is a circular dependency between 4 beans in the application context:
- courseController (field com.example.service.CourseService com.example.controller.CourseController.courseDAO)
- courseServiceRest (field private com.example.dao.CourseDAO com.example.service.CourseServiceRest.courseDAO)
- courseDAOImpl (field private org.springframework.web.client.RestTemplate com.example.dao.CourseDAOImpl.restTemplate)
- studentDAOImpl (field private org.springframework.web.client.RestTemplate com.example.dao.StudentDAOImpl.restTemplate)
- restTemplate

以下是我的代码:

我认为因为我在StudenDAOImpl和CourseDAOImpl中有相同的@bean,因为如果我删除CourseDAOImpl编译成功,代码如下:

StudentDAOImpl代码:

@Service
public class StudentDAOImpl implements StudentDAO
{
    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }

    @Override
    public StudentModel selectStudent (String npm)
    {
        StudentModel student = restTemplate.getForObject(url+npm, StudentModel.class);
        return student;
    }

    @Override
    public List<StudentModel> selectAllStudents ()
    {
       return null;
    }

}

CourseDAOImpl代码:

@Service
public class CourseDAOImpl implements CourseDAO {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Override
    public CourseModel selectCourse(String id) {
        CourseModel course = restTemplate.getForObject(urlCourse+id, CourseModel.class);
        return course;
    }

    @Override
    public List<CourseModel> selectAllCourses() {   
        return null;    
    }
}

任何答案?非常感谢你。

1 个答案:

答案 0 :(得分:1)

问题出在您的DAO中,您应该删除@Bean配置,并为每个DAO看起来如下所示

@Service
public class StudentDAOImpl implements StudentDAO
{
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public StudentModel selectStudent (String npm)
    {
        StudentModel student = restTemplate.getForObject(url+npm, StudentModel.class);
        return student;
    }

    @Override
    public List<StudentModel> selectAllStudents ()
    {
       return null;
    }

}

然后在配置Bean或入口点应用程序中,您可以添加restTemplate bean。例如,这是Config.java中的配置Bean

@Configuration
public class Config {
     @Bean
     public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
     }
}