基于java的spring配置

基于java的spring配置

java配置使用的都是java类,如下:

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.cherrypicks.hsbcpayme.cs.controller", "com.cherrypicks.hsbcpayme.service",
        "com.cherrypicks.hsbcpayme.dao"})
public class WebConfig extends WebMvcConfigurerAdapter {

    // dispatcher Servlet ,拦截请求分发请求的servlet
    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    // 过滤器
    @Bean
    public FilterRegistrationBean characterEncodingFilter(@Value("${character.encoding}") final String characterEncoding) {
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(characterEncoding);
        characterEncodingFilter.setForceEncoding(true);

        final FilterRegistrationBean reg = new FilterRegistrationBean();
        reg.setFilter(characterEncodingFilter);
        reg.addUrlPatterns("/*");
        return reg;
    }

    @Bean
    public FilterRegistrationBean corsFilter(@Value("*") final String allowedOrigins, @Value("false") final String allowCredentials) {
        return new FilterRegistrationBean(new CorsFilter(allowedOrigins, allowCredentials));
    }

    @Bean
    public FilterRegistrationBean restfulFilter() {
        final FilterRegistrationBean reg = new FilterRegistrationBean();
        reg.setFilter(new RESTfulFilter());
        reg.addUrlPatterns("/*");
        return reg;
    }

    // 拦截器
    @Bean
    public SessionInterceptor sessionInterceptor() {
        return new SessionInterceptor();
    }

    @Bean
    public IpRangeInterceptor ipRangeInterceptor() {
        return new IpRangeInterceptor();
    }

    @Bean
    public PermissionCheckInterceptor permissionCheckInterceptor() {
        return new PermissionCheckInterceptor();
    }

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        // check userId & accessToken
        registry.addInterceptor(sessionInterceptor())
        .addPathPatterns("/*")
        .excludePathPatterns("/login")
        .excludePathPatterns("/pageNotFound")
        .excludePathPatterns("/error")
        .excludePathPatterns("/checkEmail")
        .excludePathPatterns("/healthcheck");

        registry.addInterceptor(ipRangeInterceptor())
        .addPathPatterns("/*")
        .excludePathPatterns("/pageNotFound")
        .excludePathPatterns("/error");

        registry.addInterceptor(permissionCheckInterceptor())
        .addPathPatterns("/*")
        .excludePathPatterns("/login")
        .excludePathPatterns("/logout")
        .excludePathPatterns("/pageNotFound")
        .excludePathPatterns("/error");
    }
}

@Configuration:声明为配置

@EnableAutoConfiguration:自动载入应用程序所需的所有Bean——这依赖于Spring Boot在类路径中的查找。

@Bean:要载入的bean

@ComponentScan(basePackages = {"com.cherrypicks.hsbcpayme.cs.controller",

                               "com.cherrypicks.hsbcpayme.service",

                               "com.cherrypicks.hsbcpayme.dao"})

声明从哪些包中扫描了类,装配到bean

在载入bean的时候就可以根据类的实现类,设置dispatcher Servlet、过滤器、拦截器。

java数据库链接配置

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.pwd}")
    private String password;

    @Value("${srping.datasource.initialSize}")
    private Integer initialSize;
    @Value("${spring.datasource.maxActive}")
    private Integer maxActive;

    @Autowired
    private EncryptionService encryptionService;

    // system data source
    @Bean
    @Primary
    public DataSource dataSource() throws Exception {
         return tomcatPoolingDataSource();
    }

    @Bean
    public JdbcTemplate jdbcTemplate() throws Exception {
        return new JdbcTemplate(dataSource());
    }

    private DataSource tomcatPoolingDataSource() throws Exception {
        final org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(encryptionService.cherrypicksDecryption(password));

        dataSource.setInitialSize(initialSize); // 连接池启动时创建的初始化连接数量(默认值为0)
        dataSource.setMaxActive(maxActive); // 连接池中可同时连接的最大的连接数
        dataSource.setMaxIdle(5); // 连接池中最大的空闲的连接数,超过的空闲连接将被释放,如果设置为负数表示不限
        dataSource.setMinIdle(0); // 连接池中最小的空闲的连接数,低于这个数量会被创建新的连接
        dataSource.setMaxWait(60000); // 最大等待时间,当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常,如果设置-1表示无限等待
        dataSource.setRemoveAbandonedTimeout(180); // 超过时间限制,回收没有用(废弃)的连接
        dataSource.setRemoveAbandoned(true); // 超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30); // 检查无效连接的时间间隔 设为30分钟
        return dataSource;
    }
}

这里使用了Tomcat的连接池,连接后加入到JdbcTemplate。

Scheduler的Java配置

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.cherrypicks.hsbcpayme.cs.scheduler"})
public class SchedulerConfig {

    @Value("${check.email.cron:}")
    private String checkCustomerEmailCron;

    @Value("${user.profile.report.cron}")
    private String userProfileReportCron;

    @Autowired
    private DataSourceConfig dataSourceConfig;

    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    public AutowiringSpringBeanJobFactory jobFactory() {
        return new AutowiringSpringBeanJobFactory();
    }

    @Bean
    public JobDetailFactoryBean checkCustomerEmailJob(){
        final JobDetailFactoryBean factory = new JobDetailFactoryBean();
        factory.setJobClass(CheckCustomerEmailScheduler.class);
        factory.setDurability(true);
        return factory;
    }

    @Bean
    public JobDetailFactoryBean userProfileReportJob(){
        final JobDetailFactoryBean factory = new JobDetailFactoryBean();
        factory.setJobClass(UserProfileReportScheduler.class);
        factory.setDurability(true);
        return factory;
    }

    @Bean
    public CronTriggerFactoryBean checkCustomerEmailTrigger(){
        final CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean();
        stFactory.setJobDetail(checkCustomerEmailJob().getObject());
        stFactory.setCronExpression(checkCustomerEmailCron);
        stFactory.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        return stFactory;
    }

    @Bean
    public CronTriggerFactoryBean userProfileReportTrigger(){
        final CronTriggerFactoryBean stFactory = new CronTriggerFactoryBean();
        stFactory.setJobDetail(userProfileReportJob().getObject());
        stFactory.setCronExpression(userProfileReportCron);
        stFactory.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        return stFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
        final SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
        final Resource resource = resourceLoader.getResource("classpath:quartz.properties");
        scheduler.setConfigLocation(resource);
        scheduler.setDataSource(dataSourceConfig.quartzDataSource());
        // scheduler.setTransactionManager(dataSourceConfig.quartzTransactionManager());
        // This name is persisted as SCHED_NAME in db. for local testing could change to unique name to avoid collision with dev server
        scheduler.setSchedulerName("csQuartzScheduler");
        // Will update database cron triggers to what is in this jobs file on each deploy. Replaces all previous trigger and job data that was in the database.
        scheduler.setOverwriteExistingJobs(true);
        scheduler.setAutoStartup(true);
        scheduler.setJobFactory(jobFactory());
        scheduler.setJobDetails(checkCustomerEmailJob().getObject(), userProfileReportJob().getObject());
        scheduler.setTriggers(checkCustomerEmailTrigger().getObject(), userProfileReportTrigger().getObject());
        return scheduler;
    }
}

注意 

1. 每个job要定义一个detail(调用哪个类,其他详细信息),一个trigger(周期、调用哪个detail、时区)

2. 定义scheduler的时候记得设置dataSource、name、properties、detail、trigger

线程池的java配置

@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        final ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(5);
        pool.setMaxPoolSize(10);
        pool.setQueueCapacity(50);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        pool.setKeepAliveSeconds(300);
        return pool;
    }

}

关键是类ThreadPoolTaskExecutor

redis连接的java配置

@Configuration
public class RedisConfig {

    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.pwd}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.pool.max-active}")
    private int poolMaxActive;
    @Value("${spring.redis.pool.max-wait}")
    private int poolMaxWait;
    @Value("${spring.redis.pool.max-idle}")
    private int poolMaxIdle;
    @Value("${spring.redis.pool.min-idle}")
    private int poolMinIdle;

    @Autowired
    private EncryptionService encryptionService;

    @Bean
    public RedisConnectionFactory jedisConnectionFactory() throws Exception {
        final JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(poolMaxActive);
        poolConfig.setMaxIdle(poolMaxIdle);
        poolConfig.setMaxWaitMillis(poolMaxWait);
        poolConfig.setMinIdle(poolMinIdle);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestWhileIdle(true);
        final JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
        jedisConnectionFactory.setDatabase(database);
        jedisConnectionFactory.setHostName(host);
        if (StringUtils.isNotBlank(password)) {
            jedisConnectionFactory.setPassword(encryptionService.cherrypicksDecryption(password));
        }
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setTimeout(timeout);

        // 其他配置,可再次扩展
        return jedisConnectionFactory;
    }
}

javaMailSender的java配置

@Configuration
public class MailConfig {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private int port;
    @Value("${spring.mail.properties.mail.smtp.auth}")
    private boolean auth;
    @Value("${spring.mail.properties.mail.smtp.starttls.enable}")
    private boolean starttlsEnable;
    @Value("${spring.mail.properties.mail.smtp.starttls.required}")
    private boolean starttlsRequired;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.pwd}")
    private String password;

    @Autowired
    private EncryptionService encryptionService;

    @Bean
    public JavaMailSender javaMailSender() throws Exception {
        final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        final Properties mailProperties = new Properties();
        mailProperties.put("mail.smtp.auth", auth);
        mailProperties.put("mail.smtp.starttls.enable", starttlsEnable);
        mailProperties.put("mail.smtp.starttls.required", starttlsRequired);
        mailSender.setJavaMailProperties(mailProperties);
        mailSender.setHost(host);
        mailSender.setPort(port);
        // mailSender.setProtocol(protocol);
        mailSender.setUsername(username);
        if (StringUtils.isNotBlank(password)) {
            mailSender.setPassword(encryptionService.cherrypicksDecryption(password));
        }
        mailSender.setDefaultEncoding(Constants.UTF8);
        return mailSender;
    }
}

猜你喜欢

转载自youyu4.iteye.com/blog/2346809