【问题标题】:JdbcTemplate returns NullPointerException in my Implementation ClassJdbcTemplate 在我的实现类中返回 NullPointerException
【发布时间】:2021-01-31 11:50:09
【问题描述】:

您好,我是 Spring 框架的新手。我想 @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);
    }

}

AppInitialiser.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[]{"/"};
    }

}


DatabaseConfig.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;

    }
}

SecurityConfig.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

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-data-jpa


    【解决方案1】:
    @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 没用。

    【讨论】:

    • Hello Gurkan,我已将 jdbcTemplate.setDataSource(datasource) 更改为 jdbcTemplate.setDataSource(dataSource());我意识到命名约定应该更合适。顺便说一下,即使将 DatabaseConfig 添加到 AppIntializer 仍然不起作用;(
    【解决方案2】:

    我刚刚进行了这些更改,它只是给我的 Bean 一个名字并且工作了 :)

        @Bean("dataSource")
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("org.postgresql.Driver");
            dataSource.setUrl(" jdbc:postgresql://localhost:5432/test");
            dataSource.setUsername("postgres");
            dataSource.setPassword("sillicon");
            
            return dataSource;
        }
        
        @Bean("jdbcTemplate")
        public JdbcTemplate jdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多