美文网首页
springboot项目架构(3)--- webmvc,myba

springboot项目架构(3)--- webmvc,myba

作者: 贺宇_f482 | 来源:发表于2018-09-14 10:56 被阅读19次

springboot提倡0配置文件配置,改用JavaBean配置,而刚转到springboot的人不免有些无从下手,这篇文章就介绍一下,springboot的常用JavaBean配置。

1、webmvc配置

这里webmvc配置主要是添加"过滤器","拦截器",与重写接口解析方式

@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcAutoConfiguration implements WebMvcConfigurer{

    /**
     * 指定日期接口解析方式
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverter());
    }

    /**
     * 把返回Json中的null换为""
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
        return objectMapper;
    }

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> patterns = new ArrayList<>();
        patterns.add("/html/**");
        patterns.add("/script/**");
        patterns.add("/print/**");
        patterns.add("/index.html");
        patterns.add("/swagger-ui.html");
        patterns.add("/webjars/**");
        patterns.add("/swagger-resources/**");
        patterns.add("/swagger-resources/**");
        registry.addInterceptor(new SessionInterceptor()).excludePathPatterns(patterns); 
    }

    /**
     * 添加过滤器
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public FilterRegistrationBean<PageFilter> filterRegistrationBean() {
        FilterRegistrationBean<PageFilter> registrationBean = new FilterRegistrationBean<PageFilter>();
        PageFilter loginFilter = new PageFilter();
        registrationBean.setFilter(loginFilter);
        List<String> urlPatterns = new ArrayList<String>();
        urlPatterns.add("/login");
        urlPatterns.add("*.html");
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }

}

2、mybatis配置

mybatis配置是通过注入的方式实现的,只需要在webmcv配置最后添加即可

/**
 * mybatis配置
 * @return
 */
@Bean
ConfigurationCustomizer mybatisConfig(){
    return configuration -> {
        // setting
        configuration.setUseGeneratedKeys(true);
        configuration.setCacheEnabled(true);
        configuration.setLazyLoadingEnabled(true);
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        configuration.setAggressiveLazyLoading(true);

        // typeAlias
        configuration.getTypeAliasRegistry().registerAliases("com.pcbwx.jsp.bean");
    };
}

3、reids配置

我这里的redis配置比较简单,主要是配置redis所用操作类Template

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 创建redis操作实例
     * @param clazz     泛型类
     * @param connectionFactory redis连接工厂
     * @return
     */
    private <T> RedisTemplate<String, T> createTemplate(Class<T> clazz, RedisConnectionFactory connectionFactory){
        Jackson2JsonRedisSerializer<T> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<T>(
            clazz);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, T> template = new RedisTemplate<String, T>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    // --------------------注入操作类---------------------------

    @Bean
    StringRedisTemplate stringTemplate(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    @Bean
    RedisTemplate<String, Object> template(RedisConnectionFactory connectionFactory) {
        return createTemplate(Object.class, connectionFactory);
    }

    @Bean
    RedisTemplate<String, Dictionary> templateDic(RedisConnectionFactory connectionFactory) {
        return createTemplate(Dictionary.class, connectionFactory);
    }
    
}

4、log4j2配置

在springboot使用log4j2,首先需要添加jar包

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- 去除springboot默认日志logback-->
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

log4j2配置添加了线上线下环境配置,日志文件按天保存,线上环境异步输出日志。

@Plugin(name = "log4j2Config", category = ConfigurationFactory.CATEGORY)
@Order(Ordered.HIGHEST_PRECEDENCE)
@org.springframework.context.annotation.Configuration
public class Log4j2Config extends ConfigurationFactory{

    private static final String INFOAPPENDER = "myInfo";

    private static final String ERRORAPPENDER = "myError";

    private static final String CONSOLE = "Console";

    private static final String ASYNC = "ASYNC";

    private static final String FILEPATH = "/opt/logs/";

    private static final boolean dev = true;

    private Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
        builder.setConfigurationName(name);
        builder.setStatusLevel(Level.INFO);
        if (dev) {
            builder.add(getConsoleBuilder(builder));
            addDevLogger(builder);
            builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef(CONSOLE)));
        } else {
            builder.add(getErrorFileBuilder(builder));
            builder.add(getInfoFileBuilder(builder));
            builder.add(getAsyncBuilder(builder));
            builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef(ASYNC)));
        }
        return builder.build();
    }

    @Override
    public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
        return getConfiguration(loggerContext, source.toString(), null);
    }

    @Override
    public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
        ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
        return createConfiguration(name, builder);
    }

    @Override
    protected String[] getSupportedTypes() {
        return new String[] {"*"};
    }

    /**
     * 获取显示台适配器
     * @param builder
     * @return
     */
    private AppenderComponentBuilder getConsoleBuilder(
        ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder.newAppender(
              CONSOLE, "Console").addAttribute("target",
            ConsoleAppender.Target.SYSTEM_OUT);
        appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute(
            "pattern",
            "%d{HH:mm:ss} %-5level %logger{36} [%L] - %msg%n"));
        return appenderBuilder;
    }

    /**
     * 获取Error文件日志适配器
     * @param builder
     * @return
     */
    private AppenderComponentBuilder getInfoFileBuilder(
        ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder
            .newAppender(INFOAPPENDER, "RollingFile")
            .addAttribute("fileName", FILEPATH + "/info/info.log")
            .addAttribute("filePattern", FILEPATH + "/info/info-%d{yyyy-MM-dd}.log");
        appenderBuilder.add(builder.newLayout("ThresholdFilter")
            .addAttribute("level", Level.INFO)
            .addAttribute("onMatch", "ACCEPT")
            .addAttribute("onMismatch", "DENY"));
        appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute(
            "pattern",
            "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} [%L] - %msg%n"));
        appenderBuilder.add(builder.newLayout("Policies").addComponent(
            builder.newLayout("TimeBasedTriggeringPolicy")
                    .addAttribute("modulate", true)
                    .addAttribute("interval", "1")));
        return appenderBuilder;
    }

    /**
     * 获取Info文件日志适配器
     * @param builder
     * @return
     */
    private AppenderComponentBuilder getErrorFileBuilder(
        ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder
            .newAppender(ERRORAPPENDER, "RollingFile")
            .addAttribute("fileName",
                    FILEPATH + "/error/error.log")
            .addAttribute("filePattern",
                    FILEPATH + "/error/error-%d{yyyy-MM-dd}.log");
        appenderBuilder.add(builder.newLayout("ThresholdFilter")
            .addAttribute("level", Level.ERROR)
            .addAttribute("onMatch", "ACCEPT")
            .addAttribute("onMismatch", "DENY"));
        appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute(
            "pattern",
            "%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} [%L] - %msg%n"));
        appenderBuilder.add(builder.newLayout("Policies").addComponent(
            builder.newLayout("TimeBasedTriggeringPolicy")
                    .addAttribute("modulate", true)
                    .addAttribute("interval", "1")));
        return appenderBuilder;
    }

    /**
     * 获取异步写日志适配器
     * @param builder
     * @return
     */
    private AppenderComponentBuilder getAsyncBuilder(
        ConfigurationBuilder<BuiltConfiguration> builder) {
        AppenderComponentBuilder appenderBuilder = builder
            .newAppender(ASYNC, "Async");
        appenderBuilder.add(builder.newLayout("AppenderRef")
                .addAttribute("ref", INFOAPPENDER));
        appenderBuilder.add(builder.newLayout("AppenderRef")
                .addAttribute("ref", ERRORAPPENDER));
        return appenderBuilder;
    }

    /**
     * 添加debug环境
     * @param builder
     */
    private void addDevLogger(ConfigurationBuilder<BuiltConfiguration> builder){
        // 添加mybatis-debug支持
        LoggerComponentBuilder loggerMyBatisBuilder = builder
            .newLogger("com.pcbwx.jsp.dao", Level.DEBUG)
            .addAttribute("additivity", false)
            .add(builder.newAppenderRef(CONSOLE));
        builder.add(loggerMyBatisBuilder);

        // 添加spring-debug支持
        LoggerComponentBuilder loggerSpringBuilder = builder
            .newLogger("org.springframework", Level.INFO)
            .addAttribute("additivity", false)
            .add(builder.newAppenderRef(CONSOLE));
        builder.add(loggerSpringBuilder);
    }

}

github: https://github.com/HeyuRise/jsp

相关文章

网友评论

      本文标题:springboot项目架构(3)--- webmvc,myba

      本文链接:https://www.haomeiwen.com/subject/xrbngftx.html