如何制作基于构造函数或 setter 的依赖注入?

How to make constructor or setter based dependency injection?

问题是,我在 spring 中编写了简单的应用程序,它使用 jdbctemplate 从数据库中获取数据并在现场打印。我希望通过构造函数或设置器使用依赖注入来制作它(我希望看到这两种方法)。我试着自己想办法,但我对 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";
    }

您可以按照以下代码片段进行基于构造函数的依赖注入:

JdbcTemplate jdbcTemplate;

@Autowired
public HelloController(JdbcTemplate jdbcTemplate){
    this.jdbcTemplate=jdbcTemplate;
}

或者你可以做基于 setter 的依赖注入:

JdbcTemplate jdbcTemplate;

@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
    this.jdbcTemplate=jdbcTemplate;
}

首先,您应该为您的客户 class 添加 @component 注释,这样 class 将由 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; }