<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>


    posts - 10,comments - 4,trackbacks - 0
    java虛擬機可能是下面三個中的一個
    1:抽象規范
    2:一個具體實現
    3:一個虛擬機實例

    java虛擬機的生命周期
    java虛擬機的天職就是:運行一個java程序.當一個java程序運行開始運行時,一個虛擬機實例就產生了.當一個計算機上同時運行三個java程序.則將產生三個java虛擬機實例.每個程序運行在自己的虛擬機里面,不會干擾.當程序運行完畢時,虛擬機將自動退出.

    java虛擬機里面有兩種線程,守護線程和非守護線程.守護線程是說java虛擬機自己的線程,如垃圾收集線程.而非守護線程則是java中運行的程序線程.當非守護線程都運行完了.java虛擬機將退出.

    一個java虛擬機主要包括了:類轉載子系統,運行時數據區,執行引擎,內存區等等.

    運行時數據區------主要是:1 堆 2? 方法區 3 java棧

    堆和方法區對虛擬機實例中所有的對象都是共享的.而java棧區,是對每個線程都是獨立的. 當一個class被載入到 classloader中時,會解析它的類型信息.把這些類型信息放到方法區,而把程序中運行的對象,放到堆區.當一個新線程被創建,就分配一個新的java棧.java棧中保存的,是方法中的一些變量,狀態.java棧是由很多的java棧幀組成的.一個棧幀包含了一個方法運行的狀態.當一個方法被執行的時候,就壓入一個新的java棧幀到java棧中,方法返回的時候,就把棧幀彈出來,拋棄掉.


    方法區

    在java虛擬機中,被裝載的類的類型信息和類的靜態變量被存儲在方法區這樣的內存里面.java程序運行時,會查找這些個信息.方法區的大小,是動態的.也可以不是連續的.可自由在堆中分配.也可以由用戶或者程序員指定.方法區可被垃圾收集.

    方法區可以保存以下信息
    這個類型的全限定名
    直接超類的全限定名
    是類類型還是接口
    類型的訪問修飾符
    任何直接超類接口的全限定名的有序列表.
    該類型的常量池
    字段信息 類中聲明的每個字段及其順序 如字段名,類型.修飾符號.
    方法信息:如方法名,返回類型.參數表列.修飾符號.字節碼.操作數棧和棧幀中局部變量區大小等等
    類靜態變量
    一個到類classloader的引用
    一個到class類的引用



    用來存儲運行時的對象實例

    java棧
    每啟動一個新的線程.就會分配到一個java棧.java棧以幀為單位保存線程的運行狀態.它有兩種操作.入棧,出棧.
    當一個方法被調用時,入棧,當一個方法返回時,出棧,或者當方法出現異常.也出棧.

    棧幀
    組成部分 局部變量區,操作數棧,幀數據區.
    posted @ 2006-04-05 18:25 dodoma 閱讀(376) | 評論 (1)編輯 收藏
    Eliminate obsolete object references消除過期的對象引用
    When you switch from a language with manual memory management, such as C or C++, to agarbage-collected language, your job as a programmer is made much easier by the fact that your objects are automatically reclaimed when you're through with them. It seems almost like magic when you first experience it. It can easily lead to the impression that you don't have to think about memory management, but this isn't quite true.
    java中也要注意內存管理

    // Can you spot the "memory leak"?
    public class Stack {
    private Object[] elements;
    private int size = 0;
    public Stack(int initialCapacity) {
    this.elements = new Object[initialCapacity];
    }
    Effective Java: Programming Language Guide
    17
    public void push(Object e) {
    ensureCapacity();
    elements[size++] = e;
    }
    public Object pop() {
    if (size == 0)
    throw new EmptyStackException();
    return elements[--size];
    }
    /**
    * Ensure space for at least one more element, roughly
    * doubling the capacity each time the array needs to grow.
    */
    private void ensureCapacity() {
    if (elements.length == size) {
    Object[] oldElements = elements;
    elements = new Object[2 * elements.length + 1];
    System.arraycopy(oldElements, 0, elements, 0, size);
    }
    }
    }

    這里有一個內存泄漏
    如果一個棧先是增長,然后再收縮,那么,從棧中彈出來的對象將不會被當做垃圾回收,即使使用棧的客戶程序不再引用這些對象,它們也不會被回收。這是因為,棧內部維護著對這些對象的過期引用(obsolete re f e re n c e)。所謂過期引用,是指永遠也不會再被解除的引用

    改正
    public Object pop() {
    if (size==0)
    throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference清除引用
    return result;
    }

    當程序員第一次被類似這樣的問題困擾的時候,他們往往會過分小心:對于每一個對象引用,一旦程序不再用到它,就把它清空。這樣做既沒必要,也不是我們所期望的,因為這樣做會把程序代碼弄得很亂,并且可以想像還會降低程序的性能。“清空對象引用”這樣的操作應該是一種例外,而不是一種規范行為。消除過期引用最好的方法是重用一個本來已經包含對象引用的變量,或者讓這個變量結束其生命周期。如果你是在最緊湊的作用域范圍內定義每一個變量(見第2 9條),則這種情形就會自然而然地發生。應該注意到,在目前的J V M實現平臺上,僅僅退出定義變量的代碼塊是不夠的,要想使引用消失,必須退出包含該變量的方法。

    一般而言,只要一個類自己管理它的內存,程序員就應該警惕內存泄漏問題。一旦一個元素被釋放掉,則該元素中包含的任何對象引用應該要被清空。

    內存泄漏的另一個常見來源是緩存。一旦你把一個對象引用放到一個緩存中,它就很容易被遺忘掉,從而使得它不再有用之后很長一段時間內仍然留在緩存中
    posted @ 2006-03-31 16:35 dodoma 閱讀(204) | 評論 (0)編輯 收藏
    Avoid creating duplicate objects避免創建重復的對象
    It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable

    String s = new String("silly"); // DON'T DO THIS!

    String s = "No longer silly";//do this

    In addition to reusing immutable objects, you can also reuse mutable objects that you know will not be modified. Here is a slightly more subtle and much more common example of what not to do, involving mutable objects that are never modified once their values have been computed:
    除了重用非可變的對象之外,對于那些已知不會被修改的可變對象,你也可以重用它們。

    such as
    public class Person {
    private final Date birthDate;
    // Other fields omitted
    public Person(Date birthDate) {
    this.birthDate = birthDate;
    }
    // DON'T DO THIS!
    public boolean isBabyBoomer() {
    Calendar gmtCal =
    Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
    Date boomStart = gmtCal.getTime();
    gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
    Date boomEnd = gmtCal.getTime();
    return birthDate.compareTo(boomStart) >= 0 &&
    birthDate.compareTo(boomEnd) < 0;
    }
    }

    改良的版本.
    The isBabyBoomer method unnecessarily creates a new Calendar, TimeZone, and two Date instances each time it is invoked. The version that follows avoids this inefficiency with a static initializer:

    class Person {
    private final Date birthDate;
    public Person(Date birthDate) {
    this.birthDate = birthDate;
    }
    /**
    * The starting and ending dates of the baby boom.
    */
    private static final Date BOOM_START;
    private static final Date BOOM_END;
    static {
    Calendar gmtCal =
    Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
    BOOM_START = gmtCal.getTime();
    gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
    BOOM_END = gmtCal.getTime();
    }
    public boolean isBabyBoomer() {
    return birthDate.compareTo(BOOM_START) >= 0 &&
    birthDate.compareTo(BOOM_END) < 0;
    }
    }

    。一個適配器是指這樣一個對象:它把功能委
    托給后面的一個對象,從而為后面的對象提供一個可選的接口。由于適配器除了后面的對象之外,沒有其他的狀態信息,所以針對某個給定對象的特定適配器而言,它不需要創建多個適配器實例。

    This item should not be misconstrued to imply that object creation is expensive and should be avoided. On the contrary, the creation and reclamation of small objects whose constructors do little explicit work is cheap, especially on modern JVM implementations. Creating additional objects to enhance the clarity, simplicity, or power of a program is generally a good thing.
    Conversely, avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight. A prototypical example of an object that does justify an object pool is a database connection. The cost of establishing the connection is sufficiently high that it makes sense to reuse these objects. Generally speaking, however, maintaining your own object pools clutters up your code, increases memory footprint, and harms performance. Modern JVM implementations have highly optimized garbage collectors that easily outperform such object pools on lightweight objects.
    posted @ 2006-03-31 15:19 dodoma 閱讀(203) | 評論 (0)編輯 收藏
    Enforce noninstantiability with a private constructor用一個私有的構造函數來讓一個類不可以實例化

    Occasionally you'll want to write a class that is just a grouping of static methods and static fields.有時候,你想寫一個類,只是需要他提供了一系列的函數操作等,而不想讓它實例化.如:java.lang.Math or java.util.Arrays.
    但是如果你不提供構造函數,編譯器會自動添加一個.
    所以必須提供一個.此時,把構造函數設置為private.就可以達到目的.
    一般用與工具類.

    // Noninstantiable utility class
    public class UtilityClass {
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
    // This constructor will never be invoked
    }
    ... // Remainder omitted
    }

    由于private的構咱函數,該類不能被實例化.同時.不能被繼承了.
    posted @ 2006-03-30 22:22 dodoma 閱讀(216) | 評論 (0)編輯 收藏
    Enforce the singleton property with a private constructor(用私有構造函數執行單例singlton)

    A singleton is simply a class that is instantiated exactly once [Gamma98, p. 127].如數據庫資源等.
    There are two approaches to implementing singletons. Both are based on keeping the
    constructor private and providing a public static member to allow clients access to the sole
    instance of the class. In one approach, the public static member is a final field:
    // Singleton with final field
    public class Elvis {
    public static final Elvis INSTANCE = new Elvis();
    private Elvis() {
    ...
    }
    ... // Remainder omitted
    }

    1:構造函數私有
    2:提供一個靜態static的final成員

    The private constructor is called only once, to initialize the public static final field
    Elvis.INSTANCE.?
    Exactly one Elvis instance will exist once the Elvis class is initialized—no more,
    no less. Nothing that a client does can change this.

    In a second approach, a public static factory method is provided instead of the public static final field:
    // Singleton with static factory
    public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() {
    ...
    }
    public static Elvis getInstance() {
    return INSTANCE;
    }
    ... // Remainder omitted
    }

    用靜態方法返回,而不是直接返回一個實例.

    如果對對象序列化,要做多一點工作.如
    To make a singleton class serializable (Chapter 10), it is not sufficient merely to add
    implements Serializable to its declaration. To maintain the singleton guarantee, you must
    also provide a readResolve method (Item 57). Otherwise, each deserialization of a serialized instance will result in the creation of a new instance, 否則,經過對象反序列化后,會導致創建了一個新的對象.leading, in the case of our example, to spurious Elvis sightings. To prevent this, add the following readResolve method to the Elvis class:
    // readResolve method to preserve singleton property
    private Object readResolve() throws ObjectStreamException {
    /*
    * Return the one true Elvis and let the garbage collector
    * take care of the Elvis impersonator.
    */
    return INSTANCE;
    }

    posted @ 2006-03-30 17:24 dodoma 閱讀(243) | 評論 (0)編輯 收藏

    Consider providing static factory methods instead of
    constructors 考慮以靜態工廠方法取代構造函數

    The normal way for a class to allow a client to obtain an instance is to provide a public
    constructor.

    A class can provide a public static factory method, which is simply
    a static method that returns an instance of the class

    such as
    public static Boolean valueOf(boolean b) {
    return (b ? Boolean.TRUE : Boolean.FALSE);
    }

    advantages
    1:One advantage of static factory methods is that, unlike constructors, they have names.
    一個類靜態工廠方法是有名字的.If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name can make a class easier to use and the resulting client code easier to read. 如BigInteger(int, int,Random)只知道new了一個BigInteger對象,而BigInteger.probablePrime()能說明返回的可能是一個素數對象.另外,如果一個構造函數僅僅由于參數順序不同而意思也不同.靜態工廠方法就更加有用了.它更能說明函數的意思.因為它有一個名字.
    the reason?are : If the parameters to a constructor do not, describe the object being
    returned, a static factory with a well-chosen name can make a class easier to use and the
    resulting client code easier to read.

    2:A second advantage of static factory methods is that, unlike constructors, they are not
    required to create a new object each time they're invoked.每次請求時,不需要重新創建一個對象----單例的意思.這可以在任何時刻控制這個對象,同時在比較的時候也不需要用equals而用= =就可以解決了.

    3:A third advantage of static factory methods is that, unlike constructors, they can return
    an object of any subtype of their return type.可以返回一個原返回類型的子類型對象.
    One application of this flexibility is that an API can return objects without making their
    classes public.Hiding implementation classes in this fashion can lead to a very compact API.這種靈活性的一個應用是,一個A P I可以返回一個對象,同時又不使該對象的類成為公有的。以這種方式把具體的實現類隱藏起來,可以得到一個非常簡潔的A P I。這項技術非常適合
    于基于接口的框架結構,因為在這樣的框架結構中,接口成為靜態工廠方法的自然返回類型
    sample:
    // Provider framework sketch
    public abstract class Foo {
    // Maps String key to corresponding Class object
    private static Map implementations = null;
    // Initializes implementations map the first time it's called
    private static synchronized void initMapIfNecessary() {
    if (implementations == null) {
    implementations = new HashMap();
    // Load implementation class names and keys from
    // Properties file, translate names into Class
    // objects using Class.forName and store mappings.
    ...
    }
    }
    public static Foo getInstance(String key) {
    initMapIfNecessary();
    Class c = (Class) implementations.get(key);
    if (c == null)
    return new DefaultFoo();
    try {
    return (Foo) c.newInstance();
    } catch (Exception e) {
    return new DefaultFoo();
    }
    }
    }

    公有的靜態工廠方法所返回的對象的類不僅可以是非公有的,而且該類可以隨著每次調用
    而發生變化,這取決于靜態工廠方法的參數值。只要是已聲明的返回類型的子類型,都是允
    許的。而且,為了增強軟件的可維護性,返回對象的類也可以隨著不同的發行版本而不同。
    disadvantages:

    1:The main disadvantage of static factory methods is that classes without public or protected constructors cannot be subclassed.
    類如果不含公有的或者受保護的構造函數,就不能被子類化。對于公有的靜態工廠所返回的非公有類,也同樣如此

    2:A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.


    In summary, static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Avoid the reflex to provide constructors without first considering static factories because static factories are often more appropriate. If you've weighed the two options and nothing pushes you strongly in either direction, it's probably best to provide a constructor simply because it's the norm.




    posted @ 2006-03-30 17:08 dodoma 閱讀(220) | 評論 (0)編輯 收藏

    接口修改為
    package net.blogjava.dodoma.spring.aop;

    public interface HelloI {
    ?public String sayHello(String firstName,String lastName)throws Exception;
    ?}

    類修改為
    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class Hello implements HelloI {
    ?protected static final Log log=LogFactory.getLog(Hello.class);
    ?private String msg;
    ?public Hello(){}
    ?public Hello(String msg){
    ??this.msg=msg;
    ?}
    ?
    ?public String getMsg() {
    ??return msg;
    ?}
    ?public void setMsg(String msg) {
    ??this.msg = msg;
    ?}
    ?public String sayHello(String firstName, String lastName) throws Exception{
    ??// TODO Auto-generated method stub
    ??log.info("in the class "+this.getClass().getName()+"'s method sayHello()");
    ? throw new Exception("here is a exception !");
    ??return (msg+" "+firstName+" "+lastName);
    ?}
    }



    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.ThrowsAdvice;

    public class LogThrowAdvice implements ThrowsAdvice {
    ?protected static final Log log = LogFactory.getLog(LogThrowAdvice.class);
    ?public void afterThrowing(Exception e)throws Throwable{
    ??log.info("in the class "+this.getClass().getName()+"'s method afterThrowing()");
    ??log.info("the exception is "+e.getMessage());
    ?}
    }


    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.framework.ProxyFactory;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;

    public class HelloTest {
    ?protected static final Log log = LogFactory.getLog(HelloTest.class);

    ?/**
    ? * @param args
    ? * @throws Exception
    ? */
    ?public static void main(String[] args) throws Exception {
    ??// TODO Auto-generated method stub
    ??Resource rs = new ClassPathResource("beans.xml");
    ??BeanFactory bf = new XmlBeanFactory(rs);

    ??HelloI h = (HelloI) bf.getBean("theBean");
    ??log.info("starting...");
    ??try {
    ???log.info(h.sayHello("ma", "bin"));
    ??} catch (Exception e) {
    ???e.printStackTrace();
    ??}
    ??log.info("end...");
    ??
    ??
    ??ProxyFactory factory=new ProxyFactory();
    ??factory.addAdvice(new LogThrowAdvice ());
    ??factory.setTarget(new Hello("hello"));
    ??try{
    ??HelloI hi=(HelloI)factory.getProxy();
    ??hi.sayHello("ma","bin");}
    ??catch(Exception e){e.printStackTrace();}
    ?}

    }

    posted @ 2006-03-28 12:57 dodoma 閱讀(243) | 評論 (0)編輯 收藏

    LogAroundAdvice 通知
    package net.blogjava.dodoma.spring.aop;

    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class LogAroundAdvice implements MethodInterceptor {
    ?protected static final Log log = LogFactory.getLog(LogAroundAdvice.class);

    ?public Object invoke(MethodInvocation arg) throws Throwable {
    ??//?調用目標對象之前
    ??log.info("before the target object");
    ??Object val=arg.proceed();
    ? //調用目標對象之后
    ??log.info("the arg is "+arg);
    ??log.info("after the target object");
    ??return val;
    ?}

    }

    測試方法

    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.framework.ProxyFactory;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;

    public class HelloTest {
    ?protected static final Log log = LogFactory.getLog(HelloTest.class);

    ?/**
    ? * @param args
    ? * @throws Exception
    ? */
    ?public static void main(String[] args) throws Exception {
    ??// TODO Auto-generated method stub
    ??Resource rs = new ClassPathResource("beans.xml");
    ??BeanFactory bf = new XmlBeanFactory(rs);

    ??HelloI h = (HelloI) bf.getBean("theBean");
    ??log.info("starting...");
    ??try {
    ???log.info(h.sayHello("ma", "bin"));
    ??} catch (Exception e) {
    ???e.printStackTrace();
    ??}
    ??log.info("end...");
    ??
    ??
    ??ProxyFactory factory=new ProxyFactory();
    ??factory.addAdvice(new LogAroundAdvice ());
    ??factory.setTarget(new Hello("hello"));
    ??try{
    ??HelloI hi=(HelloI)factory.getProxy();
    ??hi.sayHello("ma","bin");}
    ??catch(Exception e){e.printStackTrace();}
    ?}

    }

    posted @ 2006-03-28 12:52 dodoma 閱讀(281) | 評論 (1)編輯 收藏

    接口和實現類見LogBeforeAdvice的例子
    package net.blogjava.dodoma.spring.aop;

    import java.lang.reflect.Method;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.AfterReturningAdvice;

    public class LogAfterAdvice implements AfterReturningAdvice {
    ?protected static final Log log = LogFactory.getLog(LogAfterAdvice.class);
    ?public void afterReturning(Object returnVal, Method m, Object[] args,
    ???Object target) throws Throwable {
    ??// TODO Auto-generated method stub
    ??log.info("in the class "+this.getClass().getName()+"'s method afterReturning()");

    ??log.info("the target class is:" + target.getClass().getName());
    ??log.info("the target method is:" + m.getName());

    ??for (int i = 0; i < args.length; i++) {
    ???log.info("the method's args is:" + args[i]);
    ??}
    ??
    ??log.info("the returnValue is "+returnVal);
    ??//測試,如果返回裝備發生了異常.將如何處理程序流程
    ??//throw new Exception("返回裝備發生異常");
    ?}

    }

    測試代碼

    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.framework.ProxyFactory;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;

    public class HelloTest {
    ?protected static final Log log = LogFactory.getLog(HelloTest.class);

    ?/**
    ? * @param args
    ? * @throws Exception
    ? */
    ?public static void main(String[] args) throws Exception {
    ??// TODO Auto-generated method stub
    ??Resource rs = new ClassPathResource("beans.xml");
    ??BeanFactory bf = new XmlBeanFactory(rs);

    ??HelloI h = (HelloI) bf.getBean("theBean");
    ??log.info("starting...");
    ??try {
    ???log.info(h.sayHello("ma", "bin"));
    ??} catch (Exception e) {
    ???e.printStackTrace();
    ??}
    ??log.info("end...");
    ??
    ??
    ??ProxyFactory factory=new ProxyFactory();
    ??factory.addAdvice(new LogAfterAdvice());
    ??factory.setTarget(new Hello("hello"));
    ??try{
    ??HelloI hi=(HelloI)factory.getProxy();
    ??hi.sayHello("ma","bin");}
    ??catch(Exception e){e.printStackTrace();}
    ?}

    }


    在beans.xml中加入如下代碼
    <bean id="theLogAfterAdvice" class="net.blogjava.dodoma.spring.aop.LogAfterAdvice"/>

    <property name="interceptorNames">
    ????? <list>
    ??????? <value>theLogAfterAdvice</value><!--此時直接使用advice,表明這個類所有的實例,方法,都享受advice的攔截-->
    ?????? </list>?
    </property>

    切入點可省略,如需要的話


    <!--切入點-->
    ? <!--Note: An advisor assembles pointcut and advice-->
    ? <bean id="theBeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    ??? <property name="advice">
    ????? <ref local="theLogAfterAdvice"/>
    ??? </property>
    ??? <!--匹配模式-->
    ??? <property name="pattern">
    ????? <value>.*</value>
    ??? </property>
    ? </bean>

    posted @ 2006-03-28 12:37 dodoma 閱讀(409) | 評論 (0)編輯 收藏

    接口
    package net.blogjava.dodoma.spring.aop;

    public interface HelloI {
    ?public String sayHello(String firstName,String lastName);
    ?}

    實現類
    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class Hello implements HelloI {
    ?protected static final Log log=LogFactory.getLog(Hello.class);
    ?private String msg;
    ?public Hello(){}
    ?public Hello(String msg){
    ??this.msg=msg;
    ?}
    ?public String getMsg() {
    ??return msg;
    ?}
    ?public void setMsg(String msg) {
    ??this.msg = msg;
    ?}
    ?public String sayHello(String firstName, String lastName) {
    ??// TODO Auto-generated method stub
    ??log.info("in the class "+this.getClass().getName()+"'s method sayHello()");
    ??return (msg+" "+firstName+" "+lastName);
    ?}
    }

    BeforeAdvice通知

    package net.blogjava.dodoma.spring.aop;

    import java.lang.reflect.Method;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.MethodBeforeAdvice;

    /**
    ?* 方法調用之前.
    ?* 先調用此方法
    ?* @author dodoma
    ?**/
    public class LogBeforeAdvice implements MethodBeforeAdvice {
    ?protected static final Log log = LogFactory.getLog(LogBeforeAdvice.class);

    ?public void before(Method m, Object[] args, Object target) throws Throwable {
    ??log.info("in the class "+this.getClass().getName()+"'s method before()");

    ??log.info("the target class is:" + target.getClass().getName());
    ??log.info("the target method is:" + m.getName());

    ??for (int i = 0; i < args.length; i++) {
    ???log.info("the method's args is:" + args[i]);
    ??}
    ??//測試,如果在before通知中發生了異常,程序流程將如何
    ??//throw new Exception("異常");
    ?}
    }

    測試類
    package net.blogjava.dodoma.spring.aop;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.aop.framework.ProxyFactory;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;

    public class HelloTest {
    ?protected static final Log log = LogFactory.getLog(HelloTest.class);
    ?public static void main(String[] args) throws Exception {
    ??// TODO Auto-generated method stub
    ?//應用spring的ioc容器
    ??Resource rs = new ClassPathResource("beans.xml");
    ??BeanFactory bf = new XmlBeanFactory(rs);

    ??HelloI h = (HelloI) bf.getBean("theBean");
    ??log.info("starting...");
    ??try {
    ???log.info(h.sayHello("ma", "bin"));
    ?????} catch (Exception e) {
    ???e.printStackTrace();
    ??}
    ??log.info("end...");
    ??
    ??//如果沒有使用spring的ioc,可以直接用如下代碼測試
    ??ProxyFactory factory=new ProxyFactory();
    ??factory.addAdvice(new LogBeforeAdvice());//添加通知
    ??factory.setTarget(new Hello("hello"));//添加被代理的類實例
    ??try{
    ??HelloI hi=(HelloI)factory.getProxy();
    ??hi.sayHello("ma","bin");}
    ??catch(Exception e){e.printStackTrace();}
    ?}

    }

    spring的配置文件beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "

    <beans>

    <!--享受日志的類-->
    <bean id="theTargetBean" class="net.blogjava.dodoma.spring.aop.Hello">
    ?<property name="msg">
    ??? ?<value>hello</value>
    ??? </property>
    ?????
    </bean>

    <!--advices-->
    <bean id="theLogBeforeAdvice" class="net.blogjava.dodoma.spring.aop.LogBeforeAdvice"/>

    <!--CONFIG-->
    ? <bean id="theBean" class="org.springframework.aop.framework.ProxyFactoryBean">
    ??? <!--接口-->
    ??? <property name="proxyInterfaces">
    ????? <value>net.blogjava.dodoma.spring.aop.HelloI</value>
    ??? </property>
    ??? <!--被代理的類-->
    ??? <property name="target">
    ????? <ref local="theTargetBean"/>
    ??? </property>
    ??? <!--加在代理類上的advice-->
    ??? <property name="interceptorNames">
    ????? <list>
    ??????? <value>theLogBeforeAdvice</value><!--此時直接使用advice,表明這個類所有的實例,方法,都享受advice的攔截-->
    ??????</list>
    ??? </property>
    ? </bean>
    ??
    ? <!--切入點,可以精確匹配類,方法,也可以不需要這個-->
    ? <!--Note: An advisor assembles pointcut and advice-->
    ? <bean id="theBeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    ??? <property name="advice">
    ????? <ref local="theLogBeforeAdvice"/>
    ??? </property>
    ??? <!--匹配模式-->
    ??? <property name="pattern">
    ????? <value>.*</value>
    ??? </property>
    ? </bean>
    ?? ?
    </beans>

    主站蜘蛛池模板: 亚洲AV日韩AV永久无码下载| 无遮挡国产高潮视频免费观看| 又长又大又粗又硬3p免费视频| 免费黄色app网站| 亚洲国产最大av| 毛片A级毛片免费播放| 国产精品亚洲专区在线观看| 69视频在线观看免费| 久久久久亚洲Av片无码v| 免费国产99久久久香蕉| 亚洲精品视频在线| 免费播放一区二区三区| 亚洲国产成人九九综合| 大学生美女毛片免费视频| 亚洲乱码国产乱码精华| 国产免费一区二区三区VR| 日韩在线视频免费| 亚洲人成人网站色www| 人妻无码一区二区三区免费| 亚洲美女视频一区二区三区| 亚洲免费综合色在线视频| 亚洲精品无码久久久久去q | 亚洲男人的天堂www| 国产又黄又爽又大的免费视频| 亚洲精品无码MV在线观看| 精品熟女少妇av免费久久| 亚洲国产成AV人天堂无码| 毛片网站免费在线观看| 国产成人亚洲精品无码AV大片| 亚洲一区二区三区乱码A| 久操视频在线免费观看| 亚洲自国产拍揄拍| 亚洲国产精品第一区二区三区| 免费91麻豆精品国产自产在线观看| 亚洲视频一区在线观看| 日本大片在线看黄a∨免费| 狠狠躁狠狠爱免费视频无码| 亚洲不卡视频在线观看| 亚洲第一网站男人都懂| 鲁大师在线影院免费观看 | 日韩在线视频播放免费视频完整版|