天天看點

spring全注解配置(不使用xml配置)

@EnableWebMvc
@Configuration
@ComponentScans({ @ComponentScan(basePackages = { "xxx.xxx.xxx" }),
		@ComponentScan(basePackages = { "xxx.xxx.xxx" }) })	//啟動注解的包
@Import({ xxx.class, xxx.class, xxx.class })	//假如其他配置類
@PropertySource("classpath:/settings.properties")	//相關配置
public class MainConfiguration extends WebMvcConfigurerAdapter {
	
	@Bean
	public ObjectMapper objectMapper() {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper;
	}


	@Bean
	Retrofit retrofit(@Value("${xxx}") String uri, ObjectMapper objectMapper, Executor executor,
			OkHttpClient okHttpClient) {
		return new Retrofit.Builder().baseUrl(uri).callbackExecutor(executor).client(okHttpClient)
				.addConverterFactory(JacksonConverterFactory.create(objectMapper)).build();
	}

	@Bean
	OkHttpClient okHttpClient(@Value("${xxx}") Integer timeoutSec,
			@Qualifier("retry") Interceptor interceptor) {
		long ttMS = 1000 * timeoutSec;
		return new OkHttpClient.Builder().connectTimeout(ttMS, TimeUnit.MILLISECONDS)
				.readTimeout(ttMS, TimeUnit.MILLISECONDS).writeTimeout(ttMS, TimeUnit.MILLISECONDS)
				.addInterceptor(interceptor).build();

	}

	@Qualifier("retry")
	@Bean
	Interceptor retryInterceptor(@Value("${http.retry}") Integer retry) {
		return new Interceptor() {
			@Override
			public Response intercept(Chain chain) throws IOException {
				int retryCnt = 0;
				Response response = null;
				while (retryCnt++ < retry) {
					response = chain.proceed(chain.request());
					if (response.code() == 200) {
						break;
					}
				}

				return response;
			}
		};
	}

	@Bean
	ExecutorService executors(@Value("${app.api.threadnum}") Integer maxThreadNum) {
		return Executors.newFixedThreadPool(maxThreadNum);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//攔截器
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		// jackson
		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
		mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper());
		converters.add(mappingJackson2HttpMessageConverter);

		// strong converter
		converters.add(new StringHttpMessageConverter());

	}

	@Autowired
    	Environment env;
	// 靜态資源
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String path = env.getProperty("path");
		StringBuffer buffer = new StringBuffer();
		buffer.append("file:").append(path).append("/");
		registry.addResourceHandler("/file/**").addResourceLocations(buffer.toString());
	}

	// interceptors
	@Bean
	WeiXinLoginInterceptor weiXinLoginInterceptor() {
		return new WeiXinLoginInterceptor();
	}

	
	@Bean
	SysLoginInterceptor sysLoginInterceptor() {
		return new SysLoginInterceptor();
	}

	@Bean
	public CommonsMultipartResolver multipartResolver() {

		CommonsMultipartResolver cmr = new CommonsMultipartResolver();
		return cmr;

	}
	
}

           
package cn.seventree.guest.mgmt.cfg.spring;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 資料庫相關配置
 *
 * @author cl
 * @date 2017-06-26
 * @since 1.0.0
 */
@Configuration
@MapperScan("cn.seventree.guest.mgmt.mapper")
public class DataBaseConfiguration {

    @Bean(destroyMethod = "close")
    public ComboPooledDataSource dataSource(@Value("${db.driver}") String driverClz,
        @Value("${db.url}") String uri, @Value("${db.user}") String user, @Value("${db.pwd}") String pwd,
        @Value("${db.pool.minSize}") Integer poolMinSize,
        @Value("${db.pool.maxSize}") Integer poolMaxSize,
        @Value("${db.pool.initSize}") Integer poolInitSize,
        @Value("${db.pool.idleSec}") Integer poolIdleSec,
        @Value("${db.pool.acquireIncrement}") Integer poolAcInc,
        @Value("${db.pool.acquireRetryAttempts}") Integer poolAcRetry,
        @Value("${db.pool.checkoutTimeout}") Integer poolCkTimeout
    ) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driverClz);
        dataSource.setJdbcUrl(uri);
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setMinPoolSize(poolMinSize);
        dataSource.setMaxPoolSize(poolMaxSize);
        dataSource.setInitialPoolSize(poolInitSize);
        dataSource.setMaxIdleTime(poolIdleSec);
        dataSource.setAcquireIncrement(poolAcInc);
        dataSource.setAcquireRetryAttempts(poolAcRetry);
        dataSource.setCheckoutTimeout(poolCkTimeout);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource)
        throws IOException {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);

        // mapper location
        PathMatchingResourcePatternResolver pathResolver =
            new PathMatchingResourcePatternResolver();
        sessionFactoryBean
            .setMapperLocations(pathResolver.getResources("classpath*:mapper/**/*.xml"));

        // config file
        sessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-cfg.xml"));
        return sessionFactoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager =
            new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
      return new TransactionTemplate(transactionManager);
    }
}
           
public class WebInitializerImpl extends AbstractDispatcherServletInitializer {

  @Override
  protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext
        = new AnnotationConfigWebApplicationContext();
    annotationConfigWebApplicationContext.register(MainConfiguration.class);
    return annotationConfigWebApplicationContext;
  }

  @Override
  protected String[] getServletMappings() {
    return new String[]{"/"};
  }

  @Override
  protected WebApplicationContext createRootApplicationContext() {
    // just return null
    return null;
  }
}