【发布时间】:2016-02-02 17:13:14
【问题描述】:
这是我在 application.properties 中的 spring.datasource 属性-
spring.datasource.url=jdbc:postgresql://<hostname goes here>
spring.datasource.username=<username goes here>
spring.datasource.password=password
spring.datasource.driverClassName=org.postgresql.Driver
我的主要课程如下:
@PropertySources(value = {@PropertySource("classpath:application.properties")})
@PropertySource(value = "classpath:sql.properties")
@SpringBootApplication
public class MyApp implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Override
public void run(String... strings) throws Exception {
Execute execute = new Execute();
execute.executeCleanUp();
}
}
Execute类如下:
import com.here.oat.repository.CleanUpEntries;
import com.here.oat.repository.CleanUpEntriesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.IOException;
/***
*
*/
public class Execute {
@Autowired
private CleanUpEntries cleanUpEntries;
public void executeCleanUp() throws IOException {
cleanUpEntries = new CleanUpEntriesImpl();
cleanUpEntries.delete();
}
}
这里是实现类——CleanupEntriesImpl:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class CleanUpEntriesImpl implements CleanUpEntries{
@Autowired
private JdbcTemplate jdbcTemplate;
@Value(value = "${delete.query}")
private String deleteQuery;
@Override
public int delete() {
int id= jdbcTemplate.queryForObject(deleteQuery, Integer.class);
return id;
}
}
pom.xml 有以下依赖:
<!--jdbc driver-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
<scope>runtime</scope>
</dependency>
不确定为什么调用 delete() 方法时 jdbcTemplate 对象为空。有什么想法吗?
【问题讨论】:
-
我没有使用过 spring-boot,但是你的 jdbcTemplate 是在哪里创建的?您需要将数据源传递给该权限吗?