javaconfig 项目配置demo

在这里分享一份简单纯javaconfig的配置demo,仅有配置部分。就当是自我记录吧。

首先,文件结构

Paste_Image.png

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/");
} }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,335评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,895评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,766评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,918评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,042评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,169评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,219评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,976评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,393评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,711评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,876评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,562评论 4 336
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,193评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,903评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,699评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,764评论 2 351

推荐阅读更多精彩内容