Spring框架常用配置

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容