spring基礎知識總結

IOC,DI

xml配置

beans根標籤

bean

  1. name
  2. class
  3. factory-method
  4. factory-bean
  5. init-method
  6. destroy-method
  7. scope
    • singleton
    • prototype
    • request
    • session
    • globalSession

屬性注入

property set注入

  1. name
  2. value
  3. ref

constructor-arg 構造方法注入

  1. name
  2. value
  3. ref

p命名空間注入

xmlns:p="www.springframework.org/schema/p"java

<bean name="person" class="classname" p:name="uu" p:car2-ref="car2"/>
複製代碼

SpEl注入

<bean id="car" class="classname">
    <property name="name" value="#{'奔馳'}"/>
    <property name="price" value="#{800000}"/>
</bean>
複製代碼

複雜類型

複雜類型放入property中:mysql

  1. 數組,list
<list>
    <value>1</value>
    <value>2</value>
    <value>3</value>
</list>
複製代碼
  1. map
<map>
    <entry key="aaa" value="111"/>
    <entry key="bbb" value="222"/>
    <entry key="ccc" value="333"/>
</map>
複製代碼
  1. property
<props>
    <prop key="username">root</prop>
    <prop key="password">123</prop>
</props>
複製代碼

多配置

  1. 加載多個
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext2.xml");
複製代碼
  1. 引入另外一個
<import resource="applicationContext2.xml"></import>
複製代碼

註解

  • @Component
  • @Controller :WEB 層
  • @Service :業務層
  • @Repository :持久層
  1. @Value :用於注入普通類型.
  2. @Autowired :自動裝配:
  3. @Qualifier:強制使用名稱注入.
  4. @Resource 至關於:@Autowired 和@Qualifier 一塊兒使用
  5. @Scope
  6. @PostConstruct
  7. @PreDestroy

AOP

代理機制:spring

  • Spring 的 AOP 的底層用到兩種代理機制:
    • JDK 的動態代理 :針對實現了接口的類產生代理.
    • Cglib 的動態代理 :針對沒有實現接口的類產生代理. 應用的是底層的字節碼加強的技術 生成當前類的子類對象.

JDK 動態代理

public class MyJDKProxy implements InvocationHandler {
    private UserDao userDao;
    public MyJDKProxy(UserDao userDao) {
        this.userDao = userDao;
    }
    // 編寫工具方法:生成代理:
    public UserDao createProxy(){
        UserDao userDaoProxy = (UserDao) 
        Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
        userDao.getClass().getInterfaces(), this);
        return userDaoProxy;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if("save".equals(method.getName())){
            System.out.println("權限校驗================");
        }
        return method.invoke(userDao, args);
    }
}
複製代碼

Cglib 動態代理

public class MyCglibProxy implements MethodInterceptor{
    private CustomerDao customerDao;
    public MyCglibProxy(CustomerDao customerDao){
        this.customerDao = customerDao;
    }
    // 生成代理的方法:
    public CustomerDao createProxy(){
        // 建立 Cglib 的核心類:
        Enhancer enhancer = new Enhancer();
        // 設置父類:
        enhancer.setSuperclass(CustomerDao.class);
        // 設置回調:
        enhancer.setCallback(this);
        // 生成代理:
        CustomerDao customerDaoProxy = (CustomerDao) enhancer.create();
        return customerDaoProxy;
    }
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        if("delete".equals(method.getName())){
            Object obj = methodProxy.invokeSuper(proxy, args);
            System.out.println("日誌記錄================");
            return obj;
        }
        return methodProxy.invokeSuper(proxy, args);
    }
}
複製代碼
  1. Joinpoint(鏈接點):
  2. Pointcut(切入點):
  3. Advice(通知/加強):
  4. Target(目標對象):
  5. Weaving(織入):
  6. Proxy(代理):
  7. Aspect(切面):

AOP約束sql

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
複製代碼
<!-- 配置切面類 -->
<bean id="myAspectXml" class="cn.itcast.spring.demo3.MyAspectXml"></bean>
<!-- 進行 aop 的配置 -->
<aop:config>
    <!-- pointcut切入點 expression切入點表達式、 execution(* 以後必定要有空格 -->
    <aop:pointcut expression="execution(* 包.類.*Dao.save(..))" id="pointcut1"/>
    <aop:pointcut expression="execution(* 包.類.*Dao.delete(..))" id="pointcut2"/>
    <aop:pointcut expression="execution(* 包.類.*Dao.update(..))" id="pointcut3"/>
    <aop:pointcut expression="execution(* 包.類.*Dao.find(..))" id="pointcut4"/>
    <!-- 配置切面 -->
    <aop:aspect ref="myAspectXml">
        <aop:before method="before" pointcut-ref="pointcut1"/>
        <aop:after-returning method="afterReturing" pointcut-ref="pointcut2"/>
        <aop:around method="around" pointcut-ref="pointcut3"/>
        <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut4"/>
        <aop:after method="after" pointcut-ref="pointcut4"/>
    </aop:aspect>
</aop:config>
複製代碼

報錯不用怕:express

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
  <groupId>org.aspectj</groupId >
  <artifactId>aspectjweaver</artifactId >
  <version>1.6.11</version >
</dependency>

<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
  <groupId>cglib</groupId>
  <artifactId>cglib</artifactId>
  <version>2.2.2</version>
</dependency>
複製代碼

aop註解

@Aspect
public class MyAspectAnno {
    
    @Before("MyAspectAnno.pointcut1()")
    public void before(){
        System.out.println("前置通知===========");
    }
    
    @AfterReturning("MyAspectAnno.pointcut2()")
    public void afterReturning(){
        System.out.println("後置通知===========");
    }
    
    @Around("MyAspectAnno.pointcut3()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("環繞前通知==========");
        Object obj = joinPoint.proceed();
        System.out.println("環繞後通知==========");
        return obj;
    }
    
    @AfterThrowing("MyAspectAnno.pointcut4()")
    public void afterThrowing(){
        System.out.println("異常拋出通知========");
    }
    
    @After("MyAspectAnno.pointcut4()")
    public void after(){
        System.out.println("最終通知==========");
    }
    
    @Pointcut("execution(* 包.類.save(..))")
    private void pointcut1(){}
    @Pointcut("execution(* 包.類.update(..))")
    private void pointcut2(){}
    @Pointcut("execution(* 包.類.delete(..))")
    private void pointcut3(){}
    @Pointcut("execution(* 包.類.find(..))")
    private void pointcut4(){}
}
複製代碼

spring JDBC

bean配置鏈接

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="driverClass" value="com.mysql.jdbc.Driver"/>
 <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"/>
 <property name="user" value="root"/>
 <property name="password" value="123"/>
</bean>
複製代碼

外部屬性配置

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
複製代碼

外部屬性文件引入

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 <property name="location" value="classpath:jdbc.properties"/>
</bean>


<context:property-placeholder location="classpath:jdbc.properties"/>


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="driverClass" value="${jdbc.driverClass}"/>
 <property name="jdbcUrl" value="${jdbc.url}"/>
 <property name="user" value="${jdbc.username}"/>
 <property name="password" value="${jdbc.password}"/>
</bean>
複製代碼

配置事務管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
複製代碼

配置事務的通知

<!-- 配置事務的加強 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
     <tx:attributes>
         <!-- isolation="DEFAULT" 隔離級別 propagation="REQUIRED" 傳播行爲 read-only="false" 只讀 timeout="-1" 過時時間 rollback-for="" -Exception no-rollback-for="" +Exception -->
        <tx:method name="transfer" propagation="REQUIRED"/>
     </tx:attributes>
</tx:advice>
複製代碼

配置aop

<aop:config>
 <aop:pointcut expression="execution(* cn.itcast.transaction.demo2.AccountServiceImpl.transfer(..))" id="pointcut1"/>
 <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
</aop:config>
複製代碼

註解的方式開發

<!-- 開啓註解事務管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
複製代碼

@Transactional 註解配置數組

事務傳播行爲

PROPAGION_XXX :事務的傳播行爲session

  • 保證同一個事務中
    • PROPAGATION_REQUIRED 支持當前事務,若是不存在 就新建一個(默認)
    • PROPAGATION_SUPPORTS 支持當前事務,若是不存在,就不使用事務
    • PROPAGATION_MANDATORY 支持當前事務,若是不存在,拋出異常
  • 保證沒有在同一個事務中
    • PROPAGATION_REQUIRES_NEW 若是有事務存在,掛起當前事務,建立一個新的事務
    • PROPAGATION_NOT_SUPPORTED 以非事務方式運行,若是有事務存在,掛起當前事務
    • PROPAGATION_NEVER 以非事務方式運行,若是有事務存在,拋出異常
    • PROPAGATION_NESTED 若是當前事務存在,則嵌套事務執行
相關文章
相關標籤/搜索