Spring理解IOC,DI,AOP作用,概念,理解。


IOC控制反轉:創建實例對象的控制權從代碼轉換到Spring容器。實際就是在xml中配置。配置對象

實例化對象時,進行強轉為自定義類型。默認返回類型是Object強類型。

ApplicationContext 需要引依賴。
Spring核心 依賴
context  core  beans  spEL
  //創建Spring容器   使用ApplicationContext接口new出ClassPathXmlApplicationContext實現類  ,傳參為Spring配置文件。
        ApplicationContext alc=new ClassPathXmlApplicationContext("Application.xml");
        //使用Spring容器實例化對象  。    傳參為配置文件中的bean節點
        Student stu1 = (Student)alc.getBean("stu");
        System.out.println(stu1.toString());

 

Spring配置文件中: 

 

 

 

DI: 把代碼向對象屬性或實例對象注入屬性值或域屬性的控制權限轉給Spring容器進行控制。

DI實現為對象注入屬性值  在配置文件中的bean節點進行注入

實現注入的方式很多有構造注入 set注入  p:注入 等等 。    在開發中使用頻率較多的是set注入。推薦使用set注入

<!--使用p: 進行為屬性注入和域屬性注入。     使用idea工具可alt加enter進行快捷導包。-->
    <bean id="stu" class="cn.Spring.Day04.Student" p:name="王力宏" p:age="18" p:car-ref="car"></bean>

<!--使用set注入--> <!--car類 想要在student類為car類的屬性賦值則需要引用car--> <bean id="car" class="cn.Spring.Day04.Car"> <property name="penst" value="蘭博基尼"></property> </bean> <bean id="stu1" class="cn.Spring.Day04.Student"> <!--如果是對象屬性注入 property使用value進行賦值--> <property name="name" value="小豬豬"></property> <!--如果是域屬性注入 property使用ref進行引用--> <property name="car" ref="car"></property> </bean>

 

 AOP:

AOP的作用是對方法進行增強。

未使用AOP進行方法增強:

 

 使用AOP前置增強:

1.創建一個普通類實現MethodBeforeAdvice

 

public class LoggerBore  implements MethodBeforeAdvice{
    /*MethodBeforeAdvice前置增強*/
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("記錄日志");
    }
}

 

2.配置xml:

<bean id="dao" class="cn.Spring.Day05AOP.dao.UBDaoImpl"></bean>

    <bean id="service" class="cn.Spring.Day05AOP.service.UBServiceImpl">
        <property name="dao" ref="dao"></property>
    </bean>
    <bean id="aop" class="cn.Spring.Day05AOP.aop.LoggerBore"></bean>
    <aop:config>
        <!--切點 expression表達式:切入點表達式,符合改表達式的方法可以進行增強處理。-->
        <!--表達式中:public可省,void或別的類型可以換成*  *..指的是全路徑下的service下的路徑下的方法,(..)中的“..”指的是0到多個參數-->
        <!--public void cn.Spring.Day05AOP.service.UBServiceImpl.doSome()-->
        <aop:pointcut id="mypointcut" expression="execution(* *..service.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="aop" pointcut-ref="mypointcut"></aop:advisor>
 </aop:config>

AOP后置增強則實現 AfterReturningAdvice,改一下就可以。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM