JdbcTemplate not working with autowiring [duplicate]

那年仲夏 提交于 2019-12-11 12:37:45

问题


I am creating a REST application using Springboot. After doing some research I added JdbcTemplate to it rather than working directly with Jdbc and resultsets. I have the following configuration in application.properties.

server.context-path=/foo
spring.datasource.driverClassName=com.teradata.jdbc.TeraDriver
spring.datasource.url=jdbc:teradata://url
spring.datasource.username=root
spring.datasource.password=root

My REST controller has the following code

@RestController
public class LosController {

    @CrossOrigin
    @RequestMapping("/bar")
    public String Bar(){
        Gson gson = new Gson();
        Bar bar = new Bar();
        response = gson.toJson(bar.getData());
        return response;
    }

and in this object, I have

public class Bar {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<BarObject> getData(){
        String selectSql = "SELECT * FROM BAR";
        System.out.println(selectSql);
        System.out.println(jdbcTemplate.getDataSource().toString());

        List<BarObject> barObjs = jdbcTemplate.query(selectSql, new BarMapper());       

        return barObjs;
    }
}

I went through this link and configured everything as mentioned. I am able to see the System.out.println(selectSql) working. But at the next line, I am getting a null pointer exception. So the JdbcTemplate object isn't getting the data is what I feel. How can I get this working? I am trying to not use any xml configurations, which is the reason why I went for a properties file.


回答1:


Bar is not a spring bean.

To get it working, you can annotate Bar with @Component and autowire it in LosController rather than creating with new.

@RestController
public class LosController {

    @Autowired
    private Bar bar;

    @CrossOrigin
    @RequestMapping("/bar")
    public String Bar(){
        Gson gson = new Gson();
        response = gson.toJson(bar.getData());
        return response;
    }
}

@Component
public class Bar {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public List<BarObject> getData(){
        String selectSql = "SELECT * FROM BAR";
        System.out.println(selectSql);
        System.out.println(jdbcTemplate.getDataSource().toString());

        List<BarObject> barObjs = jdbcTemplate.query(selectSql, new BarMapper());       

        return barObjs;
    }
}


来源:https://stackoverflow.com/questions/36079762/jdbctemplate-not-working-with-autowiring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!