在这里分享一份简单纯javaconfig的配置demo,仅有配置部分。就当是自我记录吧。
首先,文件结构
WebInitializer 类似于web.xml 配置项目启动需要引入的一些配置。
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
}
@Override
protected Class<?>[] getRootConfigClasses() {
//PropertiesConfig.class, DatabaseConfig.class打包在一起的时候需要调用,如果分布式,则只需要DubboConfig, SecurityConfig即可
return new Class[]{DataSourceConfig.class, ShiroConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//在这里设置的filter,全部都位于spring security filter 之后
@Override
protected Filter[] getServletFilters() {
return null;
}}
DataSourceConfig 持久层配置,我使用的mybatis
@Configuration
@ComponentScan(basePackages = "code.tianmao.h5.service")
@EnableTransactionManagement
public class DataSourceConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 数据库连接配置
*
* @return PropertiesFactoryBean
*/
@Bean
public PropertiesFactoryBean databaseProperty() {
PropertiesFactoryBean dbConfig = new PropertiesFactoryBean();
dbConfig.setLocation(new ClassPathResource("db.properties"));
return dbConfig;
}
@Bean
public PropertiesFactoryBean shiroProperty() {
PropertiesFactoryBean dbConfig = new PropertiesFactoryBean();
dbConfig.setLocation(new ClassPathResource("shiro.properties"));
return dbConfig;
}
@Bean
public DruidDataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
druidDataSource.setMaxActive(20);
druidDataSource.setInitialSize(1);
druidDataSource.setMaxWait(60000);
druidDataSource.setMinIdle(1);
druidDataSource.setTimeBetweenConnectErrorMillis(3000);
druidDataSource.setMinEvictableIdleTimeMillis(300000);
druidDataSource.setValidationQuery("SELECT 'x' FROM DUAL");
druidDataSource.setTestWhileIdle(true);
druidDataSource.setTestOnBorrow(false);
druidDataSource.setTestOnReturn(false);
return druidDataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory() {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(druidDataSource());
sqlSessionFactoryBean.setTypeAliasesPackage("code.tianmao.h5.domain");
AuditingInterceptor auditingInterceptor = new AuditingInterceptor();
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.put("dialect", "mysql");
properties.put("offsetAsPageNum", true);
properties.put("rowBoundsWithCount", true);
properties.put("reasonable", true);
pageHelper.setProperties(properties);
Interceptor[] interceptor = {auditingInterceptor, pageHelper};
sqlSessionFactoryBean.setPlugins(interceptor);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setLogImpl(Log4j2Impl.class);
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean;
}
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(druidDataSource());
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("code.tianmao.h5.dao,com.isea533.mybatis.mapper");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
Properties properties = new Properties();
properties.put("mappers", "code.tianmao.h5.sysconfig.mybatis.mapper.ExpandMapper");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer ;
}}
ShiroConfig shiro配置,需要引入oAuth2 的按照这个模式配置就行
@Configuration
public class ShiroConfig {
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager());
return authorizationAttributeSourceAdvisor;
}
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager() {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setSessionManager(defaultWebSessionManager());
defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager());
return defaultWebSecurityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/first");
shiroFilterFactoryBean.setUnauthorizedUrl("/refuse.jsp");
Map filtersMap = new HashMap<>();
filtersMap.put("authc",customFormAuthenticationFilter());
shiroFilterFactoryBean.setFilters(filtersMap);
Map chainMap = new LinkedHashMap<>();
chainMap.put("/images/**","anon");
chainMap.put("/js/**","anon");
chainMap.put("/styles/**","anon");
chainMap.put("/validatecode.jsp","anon");
chainMap.put("/common/**","anon");
chainMap.put("/logout.action","logout");
chainMap.put("/index","user");
chainMap.put("/first","user");
chainMap.put("/welcome","user");
chainMap.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(chainMap);
return shiroFilterFactoryBean;
}
/**
* 自定义form认证过虑器
* 基于Form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置
*/
@Bean
public CustomFormAuthenticationFilter customFormAuthenticationFilter() {
CustomFormAuthenticationFilter customFormAuthenticationFilter = new CustomFormAuthenticationFilter();
customFormAuthenticationFilter.setUsernameParam("username");
customFormAuthenticationFilter.setPasswordParam("password");
customFormAuthenticationFilter.setRememberMeParam("rememberMe");
return customFormAuthenticationFilter;
}
/**
* 凭证匹配器
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5"); //散列算法
hashedCredentialsMatcher.setHashIterations(1); //散列次数
return hashedCredentialsMatcher;
}
/**
*
* @return
*/
@Bean
public CustomRealm customRealm() {
CustomRealm customRealm = new CustomRealm();
customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return customRealm;
}
@Bean
public SimpleCookie simpleCookie() {
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
simpleCookie.setMaxAge(2592000);
return simpleCookie;
}
/**
* rememberMeManager管理器,写cookie,取出cookie生成用户信息
*/
@Bean
public CookieRememberMeManager cookieRememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
cookieRememberMeManager.setCookie(simpleCookie());
return cookieRememberMeManager;
}
/**
* 会话管理器
*/
@Bean
public DefaultWebSessionManager defaultWebSessionManager() {
DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
defaultWebSessionManager.setGlobalSessionTimeout(600000);
defaultWebSessionManager.setDeleteInvalidSessions(true);
return defaultWebSessionManager;
}}
WebConfig springmvc的配置
@Configuration
@ComponentScan(basePackages = {"code.tianmao.h5.controller"})
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* jsp页面解析器配置
*
* @return ViewResolver
*/
@Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setOrder(100);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public CommonsMultipartResolver commonsMultipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSize(5242880);
return commonsMultipartResolver;
}
@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
localValidatorFactoryBean.setValidationMessageSource(reloadableResourceBundleMessageSource());
return localValidatorFactoryBean;
}
@Bean
public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() {
ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
reloadableResourceBundleMessageSource.setBasenames("classpath:CustomValidationMessages");
Properties properties = new Properties();
properties.put("fileEncodings", "utf-8");
reloadableResourceBundleMessageSource.setFileEncodings(properties);
reloadableResourceBundleMessageSource.setCacheSeconds(120);
return reloadableResourceBundleMessageSource;
}
/**
* 设置springdispatch默认名字为default
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/*
* 消息转换器配置
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Charset charset = Charset.forName("UTF-8");
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper om = jacksonConverter.getObjectMapper();
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
om.setLocale(Locale.CHINA);
om.setTimeZone(TimeZone.getTimeZone("GMT+8"));
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(new MediaType("text", "plain", charset));
mediaTypeList.add(new MediaType("application", "json", charset));
jacksonConverter.setSupportedMediaTypes(mediaTypeList);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(charset);
stringConverter.setWriteAcceptCharset(false);
//保持以下顺序
converters.add(jacksonConverter);//"application/json" "application/*+json"
converters.add(new Jaxb2RootElementHttpMessageConverter());//"application/xml" "text/xml" "application/*+xml"
converters.add(new SourceHttpMessageConverter<>());//"application/xml" "text/xml" "application/*+xml"
converters.add(new AllEncompassingFormHttpMessageConverter());//"application/x-www-form-urlencoded" "multipart/form-data"
converters.add(new ByteArrayHttpMessageConverter());//"application/octet-stream" "*/*"
converters.add(stringConverter);//"text/plain" "*/*"
converters.add(new ResourceHttpMessageConverter());//"*/*"
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/styles/**").addResourceLocations("/styles/");
registry.addResourceHandler("/WEB-INF/**").addResourceLocations("/WEB-INF/");
} }