JdbcTemplate无法使用自动装配 [英] JdbcTemplate not working with autowiring
问题描述
我正在使用Springboot创建一个REST应用程序.经过研究后,我向其中添加了JdbcTemplate,而不是直接使用Jdbc和结果集.我在application.properties
中具有以下配置.
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
我的REST控制器具有以下代码
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;
}
在这个对象中,我有
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;
}
}
我通过了链接并进行了配置如前所述的一切.我能够看到System.out.println(selectSql
)的工作.但是在下一行,我得到的是null pointer exception
.因此,JdbcTemplate对象无法获得我所感觉到的数据.我该如何工作?我试图不使用任何xml配置,这就是为什么要使用属性文件的原因.
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.
推荐答案
Bar
不是spring bean.
Bar
is not a spring bean.
要使其正常工作,您可以使用@Component
注释Bar
并在LosController
中自动将其布线,而不是使用new
创建.
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;
}
}
这篇关于JdbcTemplate无法使用自动装配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!