spring(二)

spring核心是兩點,一個是 IOC 容器, 一個是 AOP 切面式服務。

IOC 容器,即控制反轉,本來是由應用程序管理對象之間的依賴關係,現在交給了容器管理,即交給了 IOC 容器。 Spring 的 IOC 主要使用 DI(注入)的方式實現的,不需要主動查找,對象的查找,定位和創建全部由容器管理。Spring的IOC 容器是一個輕量級的容器,沒有侵入性,不需要依賴容器的API,也不需要實現一些特殊接口。

AOP指的是切面式服務,提供了一種橫切性的關注點的處理方式,是一種獨立的服務,遍佈在系統的各個角落。

AOP的底層實現是 JDK 的動態代理,要了解動態代理,戳 代理--靜態代理--動態代理

接下來,我們利用 AOP 修改動態代理的實現,分爲兩種情況,用Annotation(註解)的方式和採用配置文件的方式。

1.採用註解方式去修改動態代理


// 接口  UserManager.java
 
public interface UserManager {
 
    public boolean addUser(String username, String password);
 
    public void delUser(int userId);
 
    public String findUserById(int userId);
  
    public void modifyUser(int userId, String username, String password);
 }
// 接口的實現類 UserManagerImpl.java
 
public class UserManagerImpl implements UserManager {
 
  @Override
    public boolean addUser(String username, String password) {
 
       System.out.println("------UserManagerImpl.addUser-----");
       return true;
    }
 
  @Override
    public void delUser(int userId) {
 
       System.out.println("------UserManagerImpl.delUser-----");
    }
 
  @Override
    public String findUserById(int userId) {
 
       System.out.println("------UserManagerImpl.findUserById-----");
       return "zhangsan";
    }
 
  @Override
    public void modifyUser(int userId,String username, String password) {
 
       System.out.println("------UserManagerImpl.modifyUser-----");
    
    }
 
}
//通過註解方式 提取出來一個處理類

@Aspect
public class SecurityHandler {


    //* add*(..)匹配有返回值和無返回值,方法名,參數
    //addMethod()不是一個真正的方法,只是一個標識
    //addMethod()方法沒有參數和返回值
    
    @Pointcut("execution(* add*(..))")
    private void addMethod(){};

    //After和 Before是可選項
    @After("addMethod()")
    private void checkSecurity() {

       System.out.println("--------checkSecurity-------");

   }
}
//配置配置文件 applicationContext.xml


//啓用Aspect對Annocation的支持
<aop:aspectj-autoproxy/>
<bean id="userManager" class="*.*.*.UserManagerImpl"/>
<bean id="securityHandler" class="*.*.*.SecurityHandler"/>
//測試類

public class Client {
  BeanFactory factory = new ClassPathXmlApplicationContext(applicationContext.xml);
  UserManager userManager = (UserManager )factory.getBean("userManager");
  userManager.addUser("zhangsan","123");
}

注意,在做測試的過程中需要添加兩個 jar包,org.aspectjrt和 org.aspectj.aspectjweaver

2.不採用註解,直接採用 配置文件的方式去做

//通過配置文件的方式,提取出來的代理類

public class SecurityHandler {

    private void checkSecurity() {

       System.out.println("--------checkSecurity-------");

   }
}
//將所有的都配置到配置文件中 applicationContext.xml

<bean id="userManager" class="*.*.*.UserManagerImpl"/>
<bean id="securityHandler" class="*.*.*.SecurityHandler"/>

<aop:config>
    <aop:aspect id="securityAspect" ref="securityHandler">
         <aop:pointcut id="addMethod"  expression="execution(* add*(..))"/>
         <aop:before method="checkSecurity" pointcut-ref="addMethod"/>
    </aop:aspect>


</aop:config>

其他不變。至此,我們用AOP的方式實現了代理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章