0
以下代碼會產生循環依賴性錯誤。爲什麼autowiring 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'
}
是什麼循環依賴的原因?
由於數據源有一個'@ Bean'方法,'JdbcTemplate'需要數據源,但是需要使用封閉類來創建'DataSource'。 –