春天:JDBCTemplate没有正确注入

时间:2018-10-08 17:40:51

标签: spring spring-mvc spring-boot dependency-injection

好像我在Spring项目中遇到了其他问题,我希望这里有人可以帮助我。

我的项目结构如下:Project structure

我的代码:

BookController

@Controller
public class BookController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getBookData(Book book, ModelMap model) {
        model.put("data", book.getBooks());
        return "BookView";
    }
}

图书

@Component
public class Book {
    private JdbcTemplate jdbcTemplate;
    private String title;
    private String author;
    private String isbn;

    public Book() {

    }

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

    public ModelMap getBooks() {
        ModelMap model = new ModelMap();
        String sql = "SELECT * FROM Books";
        model.put("data", jdbcTemplate.queryForList(sql));
        return model;
    }
}

AppConfig

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"models", "controllers"})
public class AppConfig {
    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/onlinelibrary");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

当尝试在Book getBooks()方法中访问jdbcTemplate时,出现了空指针异常。从本质上来说,这就像依赖项注入根本不起作用。

谢谢您的帮助!

2 个答案:

答案 0 :(得分:0)

请在Book中使用@Autowired,以便Spring可以注入实际的对象。

@Component
public class Book {

    @Autowired
    private JdbcTemplate jdbcTemplate;
}

答案 1 :(得分:0)

@Repository
public class BookDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Book> findAllBooks(){

        return jdbcTemplate.query("SELECT * FROM Books",new BeanPropertyRowMapper(Book.class)); //BeanPropertyRowMapper can be used when propertyname canbe derived from column name
    }
}

public class Book implement Serializable{
    private String title;
    private String author;
    private String isbn;

    public Book() {

    }
    //all getter setter
}