你好,我对spring框架完全陌生。我想在masterdaoimpl中@autowired 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[]{"/"};
}
}
数据库配置.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
2条答案
按热度按时间3pvhb19x1#
jdbctemplate.setdatasource(数据源);可能更合适,但这不是答案,因此可以将databaseconfig放入appinitializer
我猜组件扫描不起作用。
qcbq4gxm2#
我只是做了这些改变,它起了作用,给我的豆子起了个名字,起了作用:)