简体   繁体   中英

JdbcTemplate returns NullPointerException in my Implementation Class

Hello I'm totally new to Spring Framework. I wanted to @Autowired the JdbcTemplate inside MasterDaoImpl but it returns NullPointerException. I believe @Autowired objects are created after constructor. It returns an address if i tried to print in one of the Configuration classes. I don't know what to do? What should i do in order to make the
JdbcTemplate work inside of MasterDaoImpl. Can anyone explain why this is happening? Any Suggestions with the Configurations are appreciated.

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
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(datasource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);
    return jdbcTemplate;
}

jdbcTemplate.setDataSource(datasource); can be more appropriate but that's not the answer so you can put DatabaseConfig to AppIntializer

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

I guess ComponentScan didn't work.

I just made these changes and it worked just gave my Bean a name and worked:)

    @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);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM