欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring的基于java的项目配置示例1

程序员文章站 2022-03-13 09:18:54
...
spring的基于java的项目配置示例。


import org.springframework.web.context.AbstractContextLoaderInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

public class CmsAppInitializer extends AbstractContextLoaderInitializer {

	@Override
	protected WebApplicationContext createRootApplicationContext() {
		AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	    applicationContext.register(RootConfig.class);
	    return applicationContext;
	}

}


import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.xxx.springutil.failfast.FailFastFromPropertyAndSystemProperty;

@Configuration
@ComponentScan(basePackages={"com.xxx.cms"})
@PropertySources({
	@PropertySource(value="classpath:/hs-cms-srv-properties/hs-cms-srv-env.properties"),
	@PropertySource(value="file:${appHome}/hs-cms-srv-env.properties", ignoreResourceNotFound=true)
})
@ImportResource(value = {
	"classpath:/hs-cms-srv-config/spring-memcached.xml",
//	"classpath:/hs-cms-srv-config/spring-elasticsearch.xml",
	"classpath:/hs-cms-srv-config/spring-dubbo.xml",
	"classpath:/hs-core-srv-client-config/context-client.xml",
	"classpath:/hs-cms-srv-config/spring-redis-client.xml",
	"classpath*:/hs-mq-client-config/spring-jms-common.xml",
	"classpath*:/hs-mq-client-config/spring-jms-producer.xml"
})
@Import({
	MybatisConfig.class, 
	ElasticSearchConfig.class
	})
public class RootConfig {

	@Autowired
	Environment env;
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
		final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
		pspc.setIgnoreResourceNotFound(true);
		pspc.setIgnoreUnresolvablePlaceholders(true);
		return pspc;
	}
	
	@Bean
	public PropertiesFactoryBean appProps() {
		PropertiesFactoryBean pfb = new PropertiesFactoryBean();
		pfb.setSingleton(true);
		
		Properties properties = new Properties();
		properties.put("appEnv", env.getProperty("hs.admin.env", "dev"));
		pfb.setProperties(properties);
		
		return pfb;
	}
	
	@Bean
	public FailFastFromPropertyAndSystemProperty failFastFromPropertyAndSystemProperty() {
		FailFastFromPropertyAndSystemProperty ff = new FailFastFromPropertyAndSystemProperty();
		ff.setIfExistSystemPropertyVar("appHome");
		ff.setPropertyValueBySpring(env.getProperty("hs.cms.srv.env", "dev"));
		ff.setStopWhenPropertyEqualsThisValue("dev");
		return ff;
	}
	
	@Bean
	public ThreadPoolTaskExecutor taskExcutor() {
		ThreadPoolTaskExecutor taskExcutor = new ThreadPoolTaskExecutor();
		taskExcutor.setCorePoolSize(16);
		taskExcutor.setMaxPoolSize(32);
		taskExcutor.setQueueCapacity(64);
		return taskExcutor;
	}
	
}


import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import com.xxx.dao.GenericMybatisDao;
import com.xxx.passwordencrypt.DbPasswordFactoryBean;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class MybatisConfig {
	
	private final static String ENV_PRODUCT = "product";
	private final static String ENV_BETA = "beta";
	
	@Value("${hs.cms.srv.env}")
	private String env;
	
	@Value("${hs.cms.srv.jdbc.druid.driverClassName}")
	private String driverClassName;
	@Value("${hs.cms.srv.jdbc.druid.url}")
	private String jdbcUrl;
	@Value("${hs.cms.srv.jdbc.druid.username}")
	private String username;
	@Value("${hs.cms.srv.jdbc.druid.password}")
	private String password;
	@Value("${hs.cms.srv.jdbc.druid.initialSize}")
	private Integer initialSize;
	@Value("${hs.cms.srv.jdbc.druid.maxActive}")
	private Integer maxActive;
//	@Value("${hs.cms.srv.jdbc.druid.maxIdle}")
//	private Integer maxIdle;
	@Value("${hs.cms.srv.jdbc.druid.minIdle}")
	private Integer minIdle;
	@Value("${hs.cms.srv.jdbc.druid.maxWait}")
	private Integer maxWait;
//	@Value("${hs.cms.srv.jdbc.druid.removeAbandoned}")
//	private Boolean removeAbandoned;
//	@Value("${hs.cms.srv.jdbc.druid.removeAbandonedTimeout}")
//	private Integer removeAbandonedTimeout;
	
	private boolean needDecryptPassword() {
		return ENV_PRODUCT.equals(env) || ENV_BETA.equals(env);
	}
	
	@Bean(initMethod = "init", destroyMethod = "close")
	@DependsOn()
	public DruidDataSource dataSource() throws Exception {
		
		if (needDecryptPassword()) {
			DbPasswordFactoryBean dbPasswordFactoryBean = new DbPasswordFactoryBean();
			dbPasswordFactoryBean.setCryptWord(password);
			password = dbPasswordFactoryBean.getObject();
		}
		
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setInitialSize(initialSize);
		dataSource.setMaxActive(maxActive);
//		dataSource.setMaxIdle(maxIdle);
		dataSource.setMinIdle(minIdle);
		dataSource.setMaxWait(maxWait);
		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(false);
		dataSource.setTestWhileIdle(true);
		dataSource.setFilters("mergeStat");
		dataSource.setValidationQuery("SELECT 1");
		dataSource.setPoolPreparedStatements(true);// MySQL的4.1.0后可开启服务端PreparedStatement的缓存优化
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);// 设置单个数据库连接缓存的PreparedStatement的条数
//		dataSource.setRemoveAbandoned(removeAbandoned);
//		dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
		
//		<property name="filters" value="stat" />
//		<property name="minEvictableIdleTimeMillis" value="300000" />
//		<property name="timeBetweenEvictionRunsMillis" value="60000" />
//		<property name="validationQuery" value="SELECT 1" />
//		<property name="testWhileIdle" value="true" />
//		<property name="testOnBorrow" value="false" />
//		<property name="testOnReturn" value="false" />
		
		return dataSource;
	}
	
	@Bean
    public DataSourceTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(dataSource());
    }
	
	@Bean
	public TransactionTemplate transactionTemplate() throws Exception {
		TransactionTemplate txTemplate = new TransactionTemplate();
		txTemplate.setTransactionManager(transactionManager());
		return txTemplate;
	}
	
	@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
//        sessionFactory.setTypeAliasesPackage("com.huasheng.cms.channel.common.domain");
//        sessionFactory.setTypeHandlersPackage("com.huasheng.cms.dao.mybatis.typehandler");
        Resource configLocation = new ClassPathResource("/hs-cms-srv-mybatis/mybatis-configuration.xml");
        sessionFactory.setConfigLocation(configLocation);
        ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();   
        Resource [] mappingLocations = patternResolver.getResources("classpath*:/hs-cms-srv-mybatis/**/*Mapper.xml");
        sessionFactory.setMapperLocations(mappingLocations);
        return sessionFactory.getObject();
    }
	
	@Bean
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory());
	}
	
	@Bean
	public SqlSessionTemplate sqlSessionTemplateBatch() throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory(), ExecutorType.BATCH);
	}
	
	@Bean
	public GenericMybatisDao dao() throws Exception {
		GenericMybatisDao dao = new GenericMybatisDao();
		dao.setMybatisTemplate(sqlSessionTemplate());
		return dao;
	}
	
	@Bean
	public GenericMybatisDao batchDao() throws Exception {
		GenericMybatisDao dao = new GenericMybatisDao();
		dao.setMybatisTemplate(sqlSessionTemplateBatch());
		return dao;
	}
	
}