首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring + Eclipse 開發入門:IoC 容器與 AOP 實戰教學

     編輯:Java 相關知識

開發環境準備

  • JDK 1.4.2+,配置 JAVA_HOME、CLASSPATH、Path
  • Eclipse 3.1
  • 引用 spring.jar、commons-logging-1.0.4.jar

Eclipse Build Path 配置

業務 Bean 介面與實作

public interface ServiceBean {
  void addUser(String username, String password);
  void deleteUser(String username);
  boolean findUser(String username);
  String getPassword(String username);
}

public class MyServiceBean implements ServiceBean {
  private Map map = new HashMap<>();
  public void setUserDir(String dir) { this.dir = dir; }
  public void addUser(String username, String password) {
    if (!map.containsKey(username)) map.put(username, password);
    else throw new RuntimeException("User already exist.");
  }
  public void deleteUser(String username) {
    if (map.remove(username) == null) throw new RuntimeException("User not exist.");
  }
  public boolean findUser(String username) { return map.containsKey(username); }
  public String getPassword(String username) { return map.get(username); }
}

單元測試(無容器)

public class Main {
  public static void main(String[] args) {
    ServiceBean service = new MyServiceBean();
    service.addUser("bill", "hello");
    service.addUser("tom", "goodbye");
    service.addUser("tracy", "morning");
    System.out.println("tom's password: " + service.getPassword("tom"));
    if (service.findUser("tom")) service.deleteUser("tom");
  }
}

單元測試結果

Spring 容器管理 Bean

beans.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans>
  <bean id="service" class="com.crackj2ee.example.spring.MyServiceBean" />
</beans>

客戶端啟動容器

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
ServiceBean service = (ServiceBean) factory.getBean("service");
// 業務操作...
factory.destroySingletons();

容器管理運行結果

AOP 增強:動態織入横切關注點

日誌攔截器

public class LogAdvisor implements MethodBeforeAdvice {
  public void before(Method m, Object[] args, Object target) {
    System.out.println("[Log] " + target.getClass().getName() + "." + m.getName() + "()");
  }
}

代理配置

<bean id="serviceTarget" class="com.crackj2ee.example.spring.MyServiceBean" />
<bean id="logAdvisor" class="com.crackj2ee.example.spring.LogAdvisor" />
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="proxyInterfaces"><value>com.crackj2ee.example.spring.ServiceBean</value></property>
  <property name="target"><ref local="serviceTarget"/></property>
  <property name="interceptorNames">
    <list><value>logAdvisor</value></list>
  </property>
</bean>

AOP 代理關係圖

日誌攔截運行結果

密碼加密攔截器

public class PasswordAdvisor implements MethodInterceptor {
  public Object invoke(MethodInvocation invocation) throws Throwable {
    Object ret = invocation.proceed();
    if (ret == null) return null;
    String password = (String) ret;
    return new String(new char[password.length()]).replace('\0', '*');
  }
}
<bean id="passwordAdvisorTarget" class="com.crackj2ee.example.spring.PasswordAdvisor" />
<bean id="passwordAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  <property name="advice"><ref local="passwordAdvisorTarget"/></property>
  <property name="patterns"><list><value>.*getPassword</value></list></property>
</bean>

密碼加密結果

異常處理攔截器

public class ExceptionAdvisor implements ThrowsAdvice {
  public void afterThrowing(RuntimeException re) {
    System.out.println("[Exception] " + re.getMessage());
  }
}

異常攔截結果

總結

Spring IoC 容器管理對象生命週期,AOP 動態增強業務方法且不影響介面。核心原則:面向介面編程,利用 Java 動態代理實現鬆耦合擴展。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved