Spring理解IOC,DI,AOP作用,概念,理解。
阿新 • • 發佈:2018-11-19
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,改一下就可以。