001/* 002 * Copyright 2002-2016 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.aop.aspectj.annotation; 018 019import java.io.Serializable; 020 021import org.springframework.util.Assert; 022 023/** 024 * Decorator to cause a {@link MetadataAwareAspectInstanceFactory} to instantiate only once. 025 * 026 * @author Rod Johnson 027 * @author Juergen Hoeller 028 * @since 2.0 029 */ 030@SuppressWarnings("serial") 031public class LazySingletonAspectInstanceFactoryDecorator implements MetadataAwareAspectInstanceFactory, Serializable { 032 033 private final MetadataAwareAspectInstanceFactory maaif; 034 035 private volatile Object materialized; 036 037 038 /** 039 * Create a new lazily initializing decorator for the given AspectInstanceFactory. 040 * @param maaif the MetadataAwareAspectInstanceFactory to decorate 041 */ 042 public LazySingletonAspectInstanceFactoryDecorator(MetadataAwareAspectInstanceFactory maaif) { 043 Assert.notNull(maaif, "AspectInstanceFactory must not be null"); 044 this.maaif = maaif; 045 } 046 047 048 @Override 049 public Object getAspectInstance() { 050 if (this.materialized == null) { 051 Object mutex = this.maaif.getAspectCreationMutex(); 052 if (mutex == null) { 053 this.materialized = this.maaif.getAspectInstance(); 054 } 055 else { 056 synchronized (mutex) { 057 if (this.materialized == null) { 058 this.materialized = this.maaif.getAspectInstance(); 059 } 060 } 061 } 062 } 063 return this.materialized; 064 } 065 066 public boolean isMaterialized() { 067 return (this.materialized != null); 068 } 069 070 @Override 071 public ClassLoader getAspectClassLoader() { 072 return this.maaif.getAspectClassLoader(); 073 } 074 075 @Override 076 public AspectMetadata getAspectMetadata() { 077 return this.maaif.getAspectMetadata(); 078 } 079 080 @Override 081 public Object getAspectCreationMutex() { 082 return this.maaif.getAspectCreationMutex(); 083 } 084 085 @Override 086 public int getOrder() { 087 return this.maaif.getOrder(); 088 } 089 090 091 @Override 092 public String toString() { 093 return "LazySingletonAspectInstanceFactoryDecorator: decorating " + this.maaif; 094 } 095 096}