【发布时间】:2017-04-23 09:20:40
【问题描述】:
以下代码产生循环依赖错误。
@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'
}
循环依赖背后的原因是什么?
【问题讨论】:
-
因为数据源有
@Bean方法,所以JdbcTemplate需要数据源,但是需要封闭类来创建DataSource。
标签: java spring-boot datasource jdbctemplate