IOC和AOP理解

有时候,不是因为你没有能力,也不是因为你缺少勇气,只是因为你付出的努力还太少,所以,成功便不会走向你。而你所需要做的,就是坚定你的梦想,你的目标,你的未来,然后以不达目的誓不罢休的那股劲,去付出你的努力,成功就会慢慢向你靠近。

导读:本篇文章讲解 IOC和AOP理解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

IOC

控制:传统应用系统自己创建对象,使用spring后,由容器统一创建管理;
反转:程序不创建对象,被动接收对象,由调用者决定。
如:A对象依赖B对象,传统应用需要在A内部new B对象,使用spring后,通过依赖注入灵活调用这里用到了多态。

依赖注入(DI):当某个角色(可能是一个实例,调用者)需要另一个角色(另一个java实例,被调用者)的协助时,传统设计由调用者来创建被调用者的实例。但在spring中,由容器创建依赖注入调用者。

1、spring提供IOC容器实现两种方式

⑴ BeanFactory:IOC容器基本实现,是spring内部使用接口,不提供开发人员使用。加载配置文件时候不会创建对象,在获取(使用)对象才去创建(懒加载)
⑵ ApplicationContext:BeanFactory接口的子接口,提供更多强大的功能,一般由开发人员进行使用。加载配置文件就会创建对象(饿加载)

2、xml方式注入属性(依赖注入就是注入属性)

⑴ set注入
属性注入:

<bean id="book" class="com.xc.com.xc.entity.Book">
    <property name="bookName" value="西游记"/>
</bean>

外部类注入:

<bean id="book" class="com.xc.com.xc.entity.Book">
   <property name="author" ref="author"/>
</bean>
<bean id="author" class="com.xc.com.xc.entity.Author"/>

⑵ 构造方法注入

<bean id="book" class="com.xc.com.xc.entity.Book" >
    <constructor-arg name="id" value="1" />
    <constructor-arg name="name" value="西游记" />
</bean>

3、bean的自动装配

⑴ xml autowire 属性:byName根据名称注入,byType根据类型注入

<bean id="book" class="com.xc.com.xc.entity.Book" autowire="byType" />

⑵ 外部属性文件

<!--引入外部属性文件-->
<context:property-placeholder location="classpath:jdbc.properties" />

<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${spring.driverClassName}"/>
    <property name="url" value="${spring.url}"/>
    <property name="username" value="${spring.username}"/>
    <property name="password" value="${spring.password}"/>
</bean>
spring:
	driverClassName: com.mysql.jdbc.Driver
	url: jdbc:mysql://localhost:3306/school
	username: root
	password: 123456

3、注解

⑴ xml注解扫描

<context:component-scan base-package="com.xc" />

⑵ 注入注解
@Autowired: 默认根据类型注入,类型有多个根据名称注入。 @Autowired(required = true) 默认true找不到报错,false找不到不报错
@Qualifier:单独使用不能注入,配合@Autowired使用,根据名字注入
@Resource:默认根据名称注入,找不到根据类型注入
@Value:基本数据类型注入

4、完全注解开发

作为配置类,替代xml配置文件

@Configuration
@ComponentScan( basePackages = "com.xc")
public class SpringConfig {
}

加载配置文件

 ApplicationContext context1 = new AnnotationConfigApplicationContext(SpringConfig.class);

AOP

  1. aspect(切面):有增强方法的一个类
  2. advice(通知):增强方法
  3. target(目标):被通知对象
  4. pointcut(切点):增强具体执行的包类方法名(前、后或者环绕其中一个或者多个)
  5. jointpoint(连接点):所有可以切入的点
  6. weaving(织入):把切面应用到目标对象并创建代理对象的过程
 第一个*,返回值,后面从包到类到方法名以及括号为方法参数
execution(* com.guigu.aop.one.UserServiceImpl.*(..))

一、xml 自定义切面

public interface UserService {
    void add();
    void delete();
}

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("新增了一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }
}

public class Log3  {
    public void beforeMethod(){
        System.out.println("before---------增强");
    }
}

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">
    <!--目标类-->
    <bean id="userServiceImpl" class="com.guigu.aop.one.UserServiceImpl"/>
    <!--自定义切面-->
    <bean id="log3" class="com.guigu.aop.one.Log3"/>
    <!--aop配置-->
    <aop:config>
        <!--aop:aspect  定义切面,一般的bean就可以-->
        <aop:aspect ref="log3">
            <aop:pointcut id="ponitcut" 
            expression="execution(* com.guigu.aop.one.UserServiceImpl.*(..))"/>
            <aop:before method="beforeMethod" pointcut-ref="ponitcut"/>
        </aop:aspect>
    </aop:config>
</beans>
public class Client {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = (UserService) context.getBean("userServiceImpl");
        userService.add();
    }
}

结果:
before———增强
新增了一个用户

二、xml 实现spring接口

public class Log1 implements MethodBeforeAdvice {
    //method : 要执行的目标对象的方法
    //objects : 被调用的方法的参数
    //Object : 目标对象
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println( o.getClass().getName() + "的" + 
        method.getName() + "方法被执行了");
    }
}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">
    <!--目标类-->
    <bean id="userServiceImpl" class="com.guigu.aop.one.UserServiceImpl"/>
    <!--实现接口切面-->
    <bean id="log1" class="com.guigu.aop.one.Log1"/>
    <aop:config>
        <aop:pointcut id="ponitcut"
         expression="execution(* com.guigu.aop.one.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="log1" pointcut-ref="ponitcut"/>
    </aop:config>
</beans>

结果:
com.guigu.aop.one.UserServiceImpl的add方法被执行了
新增了一个用户

三、注解

@Component
@Aspect
public class AnnotationPointcut {
    @Pointcut(value = "execution(* com.xc.aspect.*.*(..))")
    public void pointcut(){
    }
    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知");
    }
    @After("pointcut()")
    public void after(){
        System.out.println("最终通知");
    }
    @AfterReturning("pointcut()")
    public void afterReturning(){
        System.out.println("返回通知");
    }
    @Around("pointcut()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕通知(前)");
        pjp.proceed();
        System.out.println("环绕通知(后)");
    }
    @AfterThrowing("pointcut()")
    public void AfterThrowing(){
        System.out.println("异常通知");
    }
}
@Configuration
@ComponentScan(basePackages = "com.xc")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopConfig {
}
public class Client {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        UserService userService = context.getBean("userServiceImpl", UserServiceImpl.class);
        userService.add();
    }
}

结果:
环绕通知(前)
前置通知
新增了一个用户
环绕通知(后)
最终通知
返回通知

五种切入方式

  1. 前置通知:在切入点方法之前执行
  2. 返回成功通知:在切入点方法执行成功之后执行
  3. 返回异常通知:在切入点方法抛出异常后执行
  4. 最终通知:不管切入点方法执行成功还是抛出异常都会执行
  5. 环绕通知:在切入点方法执行前后都可以执行

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/148687.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!