【问题标题】:JdbcTemplate object is null in my springboot application - using postgresJdbcTemplate 对象在我的 springboot 应用程序中为空 - 使用 postgres
【发布时间】: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 对象为空。有什么想法吗?

【问题讨论】:

标签: postgresql spring-boot


【解决方案1】:

通过从我的类中删除所有新运算符并自动装配所有内容并使 Execute 成为一个组件类,该问题得到了解决。

谢谢!

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 2018-07-26
    • 2019-02-26
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多