`

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

阅读更多
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;
	}
	
}
分享到:
评论

相关推荐

    spring-boot示例项目

    本项目示例基于spring boot 最新版本(2.1.9)实现,Spring Boot、Spring Cloud 学习示例,将持续更新…… 在基于Spring Boot、Spring Cloud 分布微服务开发过程中,根据实际项目环境,需要选择、集成符合项目...

    spring的Java项目

    这个"spring的Java项目"很可能是为了展示Spring框架的基础用法,帮助开发者理解和掌握Spring的核心概念。下面将详细解释Spring框架的一些关键知识点。 1. **IoC(Inversion of Control)控制反转**:Spring通过IoC...

    如何使用Java Spring Boot执行RAG架构GenAI项目的示例.zip

    在本示例中,我们将探讨如何使用Java Spring Boot框架来实现一个基于RAG(Red-Amber-Green)架构的GenAI项目。RAG是一种广泛应用于项目管理、风险评估和KPI跟踪的颜色编码系统,其中Red代表高风险或问题,Amber表示...

    spring famework 基于注解配置示例

    本示例将详细介绍如何使用注解配置实现Spring框架的注入。 首先,我们需要了解几个关键的注解: 1. `@Component`:这是Spring中的基础组件注解,可以标记一个类为Spring管理的bean。例如,我们可以定义一个简单的...

    (源码)基于Spring Boot和MyBatis Plus的Java示例项目.zip

    # 基于Spring Boot和MyBatis Plus的Java示例项目 ## 项目简介 本项目是一个基于Spring Boot和MyBatis Plus的Java示例项目,旨在展示如何使用Spring Boot框架结合Java基础、多线程、集合、Netty、MyBatisPlus、定时...

    基于Java和HTML的Spring Security设计源码示例

    通过本项目的源码示例,开发者不仅能够学习到如何构建一个基于Java和HTML的Spring Security设计,还能够掌握在不同场景下进行安全认证与授权的方法。这个示例为开发者提供了一个实际操作和学习Spring Security的平台...

    精通Java EE项目案例-基于Eclipse Spring Struts Hibernate光盘源码(带数据库)

    Java EE是企业级应用开发的重要框架,而"精通Java EE项目案例-基于Eclipse Spring Struts Hibernate光盘源码"的资源提供了丰富的实践学习材料,旨在帮助开发者深入了解和掌握Java后端开发技术。这个项目案例涵盖了四...

    基于Java的Spring Boot学习理解与设计源码示例

    例如在`spring-boot-example-dds` 文件夹中,开发者可能会找到用于数据源配置的XML文件,虽然Spring Boot更推荐使用Java配置来替代XML,但了解XML配置仍然是有必要的,特别是对于那些依然使用Spring老项目的维护者来...

    基于Java Spring框架的项目示例简单的“待办事项”(Todo)管理应用程序

    Java Spring框架是一个广泛...以上就是基于Java Spring框架的“待办事项”管理应用程序中涉及的主要知识点。通过学习和实践这个示例,开发者可以深入了解Spring框架如何在实际项目中发挥作用,提升开发效率和应用质量。

    基于Java语言的Spring框架示例设计源码

    本项目旨在通过一系列示例源码,向开发者展示如何利用Spring框架进行应用开发。 该项目涵盖了26个Java源文件,它们是整个应用的基础,包含了核心的业务逻辑处理。Java源文件中涉及到的类和接口定义、数据模型的构建...

    基于Java和Spring Boot的完整学习代码寄存示例

    本文档提供了一个基于Java和Spring Boot的完整学习代码寄存示例,这个示例包含了丰富的文件资源,共计282个文件,它们被精心组织以帮助开发者全面理解和掌握Spring Boot的应用开发。 这个示例项目中,包含了94个...

    纯Java Config配置的Spring MVC项目示例.zip

    在本示例中,我们探讨的是一个基于纯Java配置的Spring MVC项目。Spring MVC是Spring框架的一个重要模块,专门用于构建Web应用程序。它提供了一种模型-视图-控制器(MVC)架构,使得开发人员可以更有效地组织和管理...

    基于Java与HTML/CSS技术的Spring Boot设计源码示例

    在探讨基于Java与HTML/CSS技术的Spring Boot设计源码示例之前,我们首先要了解Spring Boot本身。Spring Boot是一种流行的Java框架,其主要目的是简化新Spring应用的初始搭建以及开发过程。它使用“约定优于配置”的...

    基于Kotlin和Spring Data的Spring Boot示例项目及启动方式.zip

    Spring Boot是一种基于Java的开源框架,用于简化新Spring应用的初始搭建以及开发过程。它使用了特定的方式来配置应用程序,以便能够迅速启动并运行。Spring Boot旨在解决配置和启动的繁琐问题,使得开发者能够更加...

    maven spring mvc示例源码

    【标题】"maven spring mvc示例源码"揭示了这是一个基于Maven构建的Spring MVC Java项目的实例。Spring MVC是Spring框架的一部分,用于构建Web应用程序,而Maven则是一个项目管理和综合工具,用于自动化构建、依赖...

    基于 Spring Security 的 JWT 示例项目.zip

    Spring Security是一种基于Java的企业级安全框架,广泛应用于Web应用程序的安全需求,提供了全面的认证和授权解决方案。JWT,即JSON Web Token,是一种用于双方之间传递安全信息的简洁的、URL安全的表示声明的方式。...

    spring-javaconfig-sample, Spring MVC/Spring Data JPA/Hibernate的spring JavaConfig示例.zip

    spring-javaconfig-sample, Spring MVC/Spring Data JPA/Hibernate的spring JavaConfig示例 spring-配置示例自 spring 3.0以来,JavaConfig特性被包含在核心 spring 模块中。 因此Java开发人员可以将 spring bean...

    spring_mongo项目示例

    在本文中,我们将深入探讨`spring_mongo`项目示例,这是一个基于Spring框架集成MongoDB数据库的应用程序实例。MongoDB是一个流行的NoSQL数据库,它以JSON格式存储数据,适合处理大规模、非结构化或半结构化数据。而...

    基于Java语言的SpringCloud练习项目源码

    基于Java语言的SpringCloud练习项目源码,不仅是一个基础的学习材料,它更是一个全面展示SpringCloud技术在微服务架构中应用的完整示例。通过这个项目,学习者可以深入理解微服务架构的设计理念,掌握SpringCloud的...

Global site tag (gtag.js) - Google Analytics