首页 > 解决方案 > JdbcTemplate 在我的实现类中返回 NullPointerException

问题描述

您好,我对 Spring Framework 完全陌生。我想@Autowired MasterDaoImpl 中的 JdbcTemplate 但它返回 NullPointerException。我相信 @Autowired 对象是在构造函数之后创建的。如果我尝试在其中一个配置类中打印,它会返回一个地址。我不知道该怎么办 ?我应该怎么做才能使
JdbcTemplate 在 MasterDaoImpl 中工作。谁能解释为什么会这样?任何有关配置的建议表示赞赏。

AppConfig.java

package com.upeg.requisition.config;

import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.upeg.requisition")

public class AppConfig implements WebMvcConfigurer {
    private static final Logger logger = Logger.getLogger(AppConfig.class);

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles.xml", "/WEB-INF/loginTiles.xml" });
        tilesConfigurer.setCheckRefresh(true);
        return tilesConfigurer;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // registry.jsp("/WEB-INF/pages/", ".jsp");
        TilesViewResolver tilesViewResolver = new TilesViewResolver();
        registry.viewResolver(tilesViewResolver);

    }

    @Bean("messageSource")
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasenames("languages/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new CookieLocaleResolver();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }

}

应用初始化程序.java

package com.upeg.requisition.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
    
        return new Class[]{SecurityConfig.class,AppConfig.class,DatabaseConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
    
        return new Class[]{};
    }

    @Override
    protected String[] getServletMappings() {
        
        return new String[]{"/"};
    }

}


数据库配置.java

package com.upeg.requisition.config;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@PropertySource(value = { "classpath:application.properties" })
@EnableTransactionManagement
@ComponentScan("com.upeg.requisition")
public class DatabaseConfig {

    private static final Logger logger = Logger.getLogger(DatabaseConfig.class);

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        return jdbcTemplate;

    }
}

安全配置.java

package com.upeg.requisition.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@ComponentScan("com.upeg.requisition")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomSuccesHandler customSuccesHandler;

    private static final Logger logger = Logger.getLogger(SecurityConfig.class);

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/css/**", "/javascript/**", "/images/**", "/fonts/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login")
                .usernameParameter("username").passwordParameter("password").successHandler(customSuccesHandler).and()
                .httpBasic().and().logout().invalidateHttpSession(true).clearAuthentication(true)
                .logoutSuccessUrl("/login").permitAll().and().csrf().disable();
        http.sessionManagement().maximumSessions(1);
        http.exceptionHandling().accessDeniedPage("/denied");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().withUser("user@user.com").password("{noop}Password1234!").roles("USER").and()
                .withUser("approver@approver.com").password("{noop}Password1234!").roles("ADMIN");
    }

}

MasterTableDao.java

public interface MasterTableDao {

    
    List<MasterCategory> getCategory();
}

MasterDaoImpl.java

package com.upeg.requisition.daoimpl;

import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.upeg.requisition.config.AppConfig;
import com.upeg.requisition.config.CustomRowMapper;
import com.upeg.requisition.dao.MasterTableDao;
import com.upeg.requisition.model.MasterCategory;


@Repository
public class MasterDaoImpl implements MasterTableDao {

    private static final Logger logger = Logger.getLogger(MasterDaoImpl.class);

    @Autowired
    JdbcTemplate jdbcTemplate;



    @Override
    public List<MasterCategory> getCategory() {

    
         return jdbcTemplate.query("select * from category",new CustomRowMapper());

    }

    
}

```[enter image description here][1]


  [1]: https://i.stack.imgur.com/xTSc4.png

标签: javaspringspring-bootspring-mvcspring-data-jpa

解决方案


@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(datasource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);
    return jdbcTemplate;
}

jdbcTemplate.setDataSource(数据源); 可能更合适,但这不是答案,因此您可以将 DatabaseConfig 放入 AppIntializer

  return new Class[]{SecurityConfig.class,AppConfig.class, DatabaseConfig.class};

我猜 ComponentScan 没用。


推荐阅读