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,改一下就可以。

 

posted @ 2018-11-19 12:02  就让文谦先行  阅读(2222)  评论(0编辑  收藏  举报