为什么自动装配jdbctemplate导致循环依赖?

时间:2017-04-23 09:20:40

标签: java spring-boot datasource jdbctemplate

以下代码会产生循环依赖性错误。

   @Controller
    public class Controllers {

        @Autowired
        JdbcTemplate jdbcTemplate;

        @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
        @ResponseBody
        public String map(){
            String sql = "INSERT INTO persons " +
                    "(id, name, surname) VALUES (?, ?, ?)";
            Connection conn = null;
            jdbcTemplate.execute("INSERT INTO persons (id, name, surname) VALUES (1, \'Name\', \'Surname\')");

            return "";
        }

        @Bean
        @Primary
        public DataSource dataSource() {
            return DataSourceBuilder
                    .create()
                    .username("root")
                    .password("root")
                    .url("jdbc:mysql://localhost:3306/people")
                    .driverClassName("com.mysql.jdbc.Driver")
                    .build();
        }


The dependencies of some of the beans in the application context form a cycle:

|  org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
↑     ↓
|  controllers (field org.springframework.jdbc.core.JdbcTemplate controllers.Controllers.jdbcTemplate)
↑     ↓
|  org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
↑     ↓
|  dataSource
└─────┘

但如果我不自动装配jdbctemplate并正常初始化

jdbcTemplate = new JdbcTemplate(dataSource());

然后不会产生错误

我有以下gradle依赖项:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.3.RELEASE")
     compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.5.2.RELEASE'
   compile(group: 'mysql', name: 'mysql-connector-java', version: '6.0.6')
    testCompile group: 'junit', name: 'junit', version: '4.12'

}

循环依赖背后的原因是什么?

1 个答案:

答案 0 :(得分:1)

你有一个循环依赖,因为JdbcTemplate需要DataSource,但是要创建DataSource,需要Controllers的实例,但因为需要JdbcTemplate它无法构造(由于循环依赖)。

你正在使用Spring Boot,但显然努力不去。移除@Bean的{​​{1}}方法,并将以下内容添加到DataSource

application.properties

使用此弹簧启动将为您提供预配置的spring.datasource.url=jdbc:mysql://localhost:3306/people spring.datasource.username=root spring.datasource.password=root

<强>临提示 你正在混合版本的Spring Boot 1.5.2和1.5.3的其他东西永远不会混合框架的版本,因为等待发生的麻烦。只需删除所有版本,并假设您正在使用带有Gradle的Spring Boot,您将拥有一个托管版本。