SpringBoot-项目初始化及配置(dao)

一、配置文件及项目初始化

       1、SpringBoot项目开发使用工具:spring tool suite
       2、项目初始化:
              新建Spring Starter Project工程,选择mybatis和web项,如果不能新建可以上SpringBoot项目建立网址新建https://start.spring.io
       3、文件介绍:
              o2oApplication.java:项目启动文件
              application.properties:重要的配置均放在这个文件中

              pom.xml中的spring-boot-starter-web:能使用main启动很大程度上决定此
       4、此时可以通过o2oApplication.java中main方法实现项目的启动
              可能会遇到如下问题:
                     1、不配置application.properties中内容时项目无法启动,将启动文件@SpringBootApplication改成@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
                     2、加入o2o前缀无法生效,将server.context-path替换成server.servlet.context-path=/o2o
                     3、@RequestMapping(value = “/hello”,method = RequestMethod.GET)中value写成name时,如果不能访问到路径将name换成value

二、配置文件pom.xml的配置

       由于SpringBoot已经自带了spring和mybatis的相关配置,所以可以去除spring、mybatis相关的配置,再将有黄线的version去除,以下为项目基础配置信息



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.2.6.RELEASE
		 
	
	com.o2o
	o2o
	0.0.1-SNAPSHOT
	o2o
	shop item

	
		UTF-8
		UTF-8
		1.8
	

	
		
		
			ch.qos.logback
			logback-classic
		

		
		
			javax.servlet
			javax.servlet-api
		
		
		
			com.fasterxml.jackson.core
			jackson-databind
		
		
		
			commons-collections
			commons-collections
			3.2.2
		
   		
			com.mchange
			c3p0
			0.9.5.4
				
		
		
			mysql
			mysql-connector-java
		
		
		
		
			net.coobird
			thumbnailator
			0.4.8
		
		
		
			com.github.penggle
			kaptcha
			2.3.2
		
		
			commons-fileupload
			commons-fileupload
			1.3.2
		
		
		
			redis.clients
			jedis
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.0.1
		
		
		
		
			com.google.zxing
			javase
			3.3.0
		
		
		
			org.quartz-scheduler
			quartz
		
		
			org.springframework
			spring-context-support
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
		
			com.alibaba
			fastjson
			1.2.45
		
		
		
			com.squareup.okhttp3
			okhttp
		
      	
			com.google.code.gson
			gson
		
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.1.2
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
			
				
					org.junit.vintage
					junit-vintage-engine
				
			
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



三、数据库连接相关的配置(SpringBoot核心是去xml化,所以将减少xml的配置通过类去实现xml中的配置要求)

       1、配置数据库连接信息(application.properties)

#DataSource
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/o2o?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
#可对以上信息加密
jdbc.username=root
jdbc.password=admin

       2、mybatis-config.xml迁移




	
	
		
		

		
		

		
		
	

application.properties中关于mybatis的配置信息

#Mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
type_alias_package=com.imooc.entity

       3、DES加密算法(数据库用户名密码加密)

package com.imooc.o2o.util;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * DES是一种对称加密算法,所谓对称加密算法即:加密和解密使用相同密钥的算法。
 * 
 * @author xiangze
 *
 */
public class DESUtil {

	private static Key key;
	// 设置密钥key
	private static String KEY_STR = "myKey";
	private static String CHARSETNAME = "UTF-8";
	private static String ALGORITHM = "DES";

	static {
		try {
			// 生成DES算法对象
			KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
			// 运用SHA1安全策略
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			// 设置上密钥种子
			secureRandom.setSeed(KEY_STR.getBytes());
			// 初始化基于SHA1的算法对象
			generator.init(secureRandom);
			// 生成密钥对象
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取加密后的信息
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncryptString(String str) {
		// 基于BASE64编码,接收byte[]并转换成String
		BASE64Encoder base64encoder = new BASE64Encoder();
		try {
			// 按UTF8编码
			byte[] bytes = str.getBytes(CHARSETNAME);
			// 获取加密对象
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 初始化密码信息
			cipher.init(Cipher.ENCRYPT_MODE, key);
			// 加密
			byte[] doFinal = cipher.doFinal(bytes);
			// byte[]to encode好的String并返回
			return base64encoder.encode(doFinal);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取解密之后的信息
	 * 
	 * @param str
	 * @return
	 */
	public static String getDecryptString(String str) {
		// 基于BASE64编码,接收byte[]并转换成String
		BASE64Decoder base64decoder = new BASE64Decoder();
		try {
			// 将字符串decode成byte[]
			byte[] bytes = base64decoder.decodeBuffer(str);
			// 获取解密对象
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 初始化解密信息
			cipher.init(Cipher.DECRYPT_MODE, key);
			// 解密
			byte[] doFinal = cipher.doFinal(bytes);
			// 返回解密之后的信息
			return new String(doFinal, CHARSETNAME);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		System.out.println(getEncryptString("root"));
		System.out.println(getEncryptString("Xiangze230!"));
	}

}

       4、通过类实现DataSource(数据库连接相关信息)

package com.imooc.o2o.config.dao;

import java.beans.PropertyVetoException;

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 com.imooc.o2o.util.DESUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 配置dataSource到ioc的容器里
 * @author 释然先生
 *
 */
// 1、@Configuration标注是配置文件
@Configuration
// 2、配置mybatis mapper的扫描路径
@MapperScan("com.imooc.o2o.dao")
public class DataSourceConfiguration {

	// 3、从application。properties中读取DataSource的相关信息,通过@Value读取,${}获取即可
	@Value("${jdbc.driver}")
	private String jdbcDriver;
	@Value("${jdbc.url}")
	private String jdbcUrl;
	@Value("${jdbc.username}")
	private String jdbcUsername;
	@Value("${jdbc.password}")
	private String jdbcPassword;
	
	// 4、生成与spring-dao.xml对应的Bean DataSource
	// 4.1 数据库连接池
	@Bean(name = "dataSource")
	public ComboPooledDataSource createDataSource() throws PropertyVetoException {
		// 生成datasource实例
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		// 跟配置文件一样设置以下信息
		// 驱动
		dataSource.setDriverClass(jdbcDriver);
		// 数据库连接URL
		dataSource.setJdbcUrl(jdbcUrl);
		// 设置用户名
		dataSource.setUser(DESUtil.getDecryptString(jdbcUsername));
		// 设置用户密码
		dataSource.setPassword(DESUtil.getDecryptString(jdbcPassword));
		// 配置c3p0连接池的私有属性
		// 连接池最大线程数
		dataSource.setMaxPoolSize(30);
		// 连接池最小线程数
		dataSource.setMinPoolSize(10);
		dataSource.setInitialPoolSize(10);
		// 关闭连接后不自动commit
		dataSource.setAutoCommitOnClose(false);
		// 连接超时时间
		dataSource.setCheckoutTimeout(10000);
		// 连接失败重试次数
		dataSource.setAcquireRetryAttempts(2);
		return dataSource;
	}
	
}

       5、sqlSessionFactoryBean创建

package com.imooc.o2o.config.dao;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
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.core.io.support.ResourcePatternResolver;

@Configuration
public class SessionFactoryConfiguration {
	// 5.1 mybatis-config.xml配置文件的路径 "mybatis-config.xml"
	@Value("${mybatis_config_file}")
	private static String mybatisConfigFile;
	public void setMybatisConfigFile(String mybatisConfigFile) {
		SessionFactoryConfiguration.mybatisConfigFile = mybatisConfigFile;
	}

	// 5.2 mybatis mapper文件所在路径,扫码路径 "/mapper/**.xml" 
	@Value("${mapper_path}")
	private static String mapperPath;
	public void setMapperPath(String mapperPath) {
		SessionFactoryConfiguration.mapperPath = mapperPath;
	}

	// 5.3 实体类所在的package "com.imooc.entity"
	@Value("${type_alias_package}")
	private String typeAliasPackage;

	@Autowired
	private DataSource dataSource;

	/**
	 * 5、创建sqlSessionFactoryBean 实例 并且设置configtion 设置mapper 映射路径 设置datasource数据源
	 * 
	 * @return
	 * @throws IOException
	 */
	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 设置mybatis configuration 扫描路径
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile));
		// 添加mapper 扫描路径
		PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
		sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
		// 设置dataSource
		sqlSessionFactoryBean.setDataSource(dataSource);
		// 设置typeAlias 包扫描路径
		sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
		return sqlSessionFactoryBean;
	}

}

你可能感兴趣的:(Java,SpringBoot)