问题是,我在spring编写了一个简单的应用程序,它使用jdbctemplate从数据库中获取数据并在现场打印。我想通过构造函数或setter使用依赖注入来创建它(我希望看到这两种方法)。我试图自己解决这个问题,但是我对Spring的经验很少,所以我无法让它发挥作用。任何人都可以为我提供解决方案,如何使用下面的代码完成?
public class Customer {
private long id;
private String firstName, lastName;
public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
控制器:
@Controller
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
Customer customer;
@RequestMapping("/hello")
public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
model.addAttribute("name", name);
return "hello";
}
@RequestMapping("/getMock")
public String getMock(Model model) {
JdbcTemplate mock = Mockito.mock(JdbcTemplate.class);
List fakeList = new ArrayList<>();
fakeList.add(new Customer(1l, "sth", "sth2"));
Mockito.when(mock.query(any(String.class), any(RowMapper.class))).thenReturn(fakeList);
List<Customer> mockResult = mock.query(
"SELECT id, first_name, last_name FROM customers",
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
);
String result = null;
for(Customer customer : mockResult) result += (customer.toString() + "<br>");
model.addAttribute("mockString", result);
return "hello";
}
@RequestMapping("/getDatabase")
public String getDatabase(Model model) {
List<Customer> list = jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers",
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
);
String result = null;
for (Customer customer : list) result += (customer.toString() + "<br>");
model.addAttribute("databaseString", result);
return "hello";
}
答案 0 :(得分:0)
您可以按照以下代码段进行基于构造函数的依赖注入:
JdbcTemplate jdbcTemplate;
@Autowired
public HelloController(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
或者你可以将基于setter的依赖注入做为:
JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
答案 1 :(得分:0)
首先,您应该向Customer类添加@component
注释,以便此类将由spring管理。然后在您的控制器中注入客户属性
3种选择:
1)
@Autowired
Customer customer;
2)
@Autowired
public void setCustomer(Customer customer) {
this.customer = customer;
}
3)
@Autowired
public HelloController(Customer customer) {
this.customer = customer;
}