Spring:
Spring构建bean的时候依赖类的空参构造
依赖注入:
//实现类依赖接口,子类依赖父类,类属性包含(依赖)另一个类...
面向切面编程
声明式事务
三种开发模式:
纯XML,XML+Annotation,纯Annotation
<!-- pom.xml中添加依赖 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
XML版本:
<!-- applicationContext.xml -->
<!-- bean默认情况是单例模式 -->
<!-- 多例:scope:prototype -->
<!-- bean默认情况是饿汉模式 -->
<!-- 懒汉模式:lazy-init:true -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd">
<bean id="bean类型" class="类全名" scope="prototype"/>
<bean id="bean类型" class="类全名">
<!-- 如果绑定的属性是基本类型,则使用value属性 -->
<!-- 如果绑定的属性是 对象类型,则设置ref=该类型的id,并且必须提供该属性的set方法 -->
<property name="属性名" ref="类型的id值"/>
</bean>
<!-- 构造器注入 -->
<bean id="str" class="java.lang.String">
<constructor-arg value="Hello World!"/>
</bean>
<!-- 集合注入 -->
<bean id="list" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>潘玮婷</value>
<value>韩承霄</value>
<value>韩想想</value>
</list>
</constructor-arg>
</bean>
<!-- 配置注入 -->
<bean id="prop" class="java.util.Properties">
<constructor-arg>
<props>
<prop key="美">潘玮婷</prop>
<prop key="帅">韩承霄</prop>
<prop key="萌">韩想想</prop>
</props>
</constructor-arg>
</bean>
<!-- Map注入 -->
<bean id="map" class="java.util.HashMap">
<constructor-arg>
<map>
<entry key="美" value="潘玮婷"/>
<entry key="帅" value="韩承霄"/>
<entry key="萌" value="韩想想"/>
</map>
</constructor-arg>
</bean>
</beans>
XML+Annotation
//业务@Service 控制器@Controller 持久层@repository @Bean
//在需要用到的属性上打自动装配@Autowired注解
//接口不可以打注解
<!-- applicationContext.xml -->
<!-- Spring自动装配,自动注入 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="需要扫描的包"/>
</beans>
Annotation版本
//业务@Service 控制器@Controller 持久层@repository @Bean
//在需要用到的属性上打自动装配@Autowired注解
//接口不可以打注解
//编写Spring配置类
//生命本类是Spring配置类
@Configuration
//扫描包(默认是本类所在包及子包)
@ComponentScan
public class AppConfig {
//配置bean对象
@Bean
String pwt() {
return "潘玮婷";
}
}
AOP(面向切面编程):
//将Advice(共性代码)抽取封装成类
//纯Annotation版本
@Aspect
@Component
@EnableAspectJAutoProxy
public class LogAdvice {
@Before("execution(权限修饰符 需要匹配的方法全名(..))")
void before(JoinPoint jp) {
}
@After("execution(权限修饰符 需要匹配的方法全名(..))")
void after(JoinPoint jp) {
}
@Afterreturning("execution(权限修饰符 需要匹配的方法全名(..))")
void afterreturning(JoinPoint jp) {
}
@Afterthrowing("execution(权限修饰符 需要匹配的方法全名(..))")
void afterthrowing(JoinPoint jp) {
}
@Around("execution(权限修饰符 需要匹配的方法全名(..))")
void around(JoinPoint jp) {
}
}
<!-- XML版本 -->
<!-- 配置通知 -->
<bean id="Advice的ID" class="Advice类全名"/>
<!-- 配置切面(aspect = advice + pointcut) -->
<aop:config>
<aop:aspect ref="Advice的ID">
<!-- 配置切点表达式 -->
<aop:before method="Advice中需要被执行的方法名"
pointcut="execution(权限修饰符 需要匹配的方法全名(..))"/>
</aop:aspect>
</aop:config>
public class Advice类 {
void before(JoinPoint jp) {
}
}
<!-- XML+Annotation版本 -->
<!--开启注解扫描-->
<context:component-scan base-package="com.gem"/>
<!--开启AOP-->
<aop:aspectj-autoproxy/>
//组件
@Component
//注解配置切面
@Aspect
public class LogAdvice {
//注解配置切点表达式
@After("execution(权限修饰符 需要匹配的方法全名(..))")
public void log(JoinPoint jp) {
}
}
Around纯注解
//在Appconfig(配置类)中加上@EnableAspectJAutoProxy(proxyTargetClass = true)注解
//即可解决自动默认使用接口代理的错误
//在Advcie类中编写的被Around注解修饰的方法中使用ProceedingJoinPoint类中的proceed()方法获取被环绕的方法中的执行语句
//其余配置同纯注解版本的所有配置
声明式事务:
<!-- applicationContext.xml中需要的配置 -->
<!-- JAVA类中的注解同XML+Annotation版本 -->
<!-- Hibernate+Spring版本 -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启包扫描,配置 -->
<context:component-scan base-package="com.spring.annotation"/>
<!--开启面向切面-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 导入外部数据库配置文件 -->
<context:property-placeholder location="数据库配置文件路径"/>
<!-- 配置数据源出c3p0 -->
<bean id="dataSource" class="数据源全类名">
<property name="key" value="${key}"/>
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="持久层的SessionFactory全类名">
<!-- 整合数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置持久层框架 -->
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="事务管理器全类名">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置内置环绕 -->
<tx:advice id="环绕id" transaction-manager="transactionManager">
<tx:attributes>
<!-- 设置事务隔离级别以及传播行为 -->
<tx:method name="*" isolation="隔离级别" propagation="事务传播机制"/>
</tx:attributes>
</tx:advice>
<!-- 配置声明式事务切面 -->
<aop:config>
<aop:advisor advice-ref="环绕id" pointcut="execution(权限修饰符 需要匹配的方法全名(..))"/>
</aop:config>
</beans>
//纯注解版本Hibernate+Spring
package com.spring.annotation;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
/*
* Spring主配置类
* */
//声明配置类
@Configuration
//扫描包(默认是本类所在包及子包)
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement
@PropertySource("classpath:db.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
DataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(env.getProperty("driverClass"));
dataSource.setJdbcUrl(env.getProperty("jdbcUrl"));
dataSource.setUser(env.getProperty("user"));
dataSource.setPassword(env.getProperty("password"));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("maxPoolSize")));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("minPoolSize")));
dataSource.setMaxStatements(Integer.parseInt(env.getProperty("maxStatements")));
dataSource.setIdleConnectionTestPeriod(Integer.parseInt(env.getProperty("idleConnectionTestPeriod")));
dataSource.setUnreturnedConnectionTimeout(Integer.parseInt(env.getProperty("unreturnedConnectionTimeout")));
dataSource.setAcquireIncrement(Integer.parseInt(env.getProperty("acquireIncrement")));
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource());
Properties properties = new Properties();
properties.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.jdbc.batch_size", "50");
localSessionFactoryBean.setHibernateProperties(properties);
localSessionFactoryBean.setPackagesToScan("com.spring.annotation.entity");
return localSessionFactoryBean;
}
@Bean
HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
Mybatis整合Spring
<!-- applicationContext.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="扫描包名"/>
<!--开启AOP-->
<aop:aspectj-autoproxy/>
<!--开启声明式事务-->
<tx:annotation-driven/>
<!--导入外部数据库配置文件-->
<context:property-placeholder location="db.properties"/>
<!--配置数据源,Commons-DBCP2-->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxTotal" value="${maxTotal}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="maxWaitMillis" value="${maxWaitMillis}"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--整合数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis-->
<property name="configLocation" value="mybatis.xml"/>
<!--配置mapper映射文件-->
<property name="mapperLocations" value="classpath:com/hcx/market/mapper/*.xml"/>
</bean>
<!--Mapper接口扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper所在的包名"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
<!--Mybatis.xml-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 开启延迟加载的支持 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 日志的设置 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 别名的设置 全类路径名改成 类名 ,简化写法-->
<typeAliases>
<!-- 该包下面的实体类全部采用别名的方式 -->
<package name="实体类所在包"/>
</typeAliases>
<!--使用mybatis内置枚举转换器(默认是String,这里设置成Ordinal)-->
<typeHandlers>
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
javaType="枚举类全名"/>
</typeHandlers>
<!--分页插件-->
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
<!--<property name="param1" value="value1"/>-->
</plugin>
</plugins>
</configuration>
//纯注解配置-配置类
import com.github.pagehelper.PageInterceptor;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
//声明配置类
@Configuration
//扫描包(默认是本类所在包及子包)
@ComponentScan
//开启切面编程
@EnableAspectJAutoProxy(proxyTargetClass = true)
//开启声明式事务
@EnableTransactionManagement
//Spring开启Mapper包扫描
@MapperScan(basePackages = "com.hcx.market.mapper")
public class AppConfig {
@Bean
//配置数据源
DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
try {
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setInitialSize(10);
dataSource.setMaxTotal(5);
dataSource.setMaxIdle(5);
dataSource.setMaxWaitMillis(5000);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
//配置SessionBean工厂
SqlSessionFactoryBean sqlSessionFactory() {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setTypeAliasesPackage("com.hcx.market.entity");
//枚举转换器
// sqlSessionFactoryBean.setTypeHandlers(new EnumOrdinalTypeHandler());
sqlSessionFactoryBean.setPlugins(new PageInterceptor());
return sqlSessionFactoryBean;
}
@Bean
//配置事务管理器
DataSourceTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
return dataSourceTransactionManager;
}
}