001/* 002 * Copyright 2002-2017 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.config; 018 019import org.springframework.aop.aspectj.AspectInstanceFactory; 020import org.springframework.beans.factory.BeanFactory; 021import org.springframework.beans.factory.BeanFactoryAware; 022import org.springframework.beans.factory.config.ConfigurableBeanFactory; 023import org.springframework.core.Ordered; 024import org.springframework.util.Assert; 025import org.springframework.util.ClassUtils; 026 027/** 028 * Implementation of {@link AspectInstanceFactory} that locates the aspect from the 029 * {@link org.springframework.beans.factory.BeanFactory} using a configured bean name. 030 * 031 * @author Rob Harrop 032 * @author Juergen Hoeller 033 * @since 2.0 034 */ 035public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstanceFactory, BeanFactoryAware { 036 037 private String aspectBeanName; 038 039 private BeanFactory beanFactory; 040 041 042 /** 043 * Set the name of the aspect bean. This is the bean that is returned when calling 044 * {@link #getAspectInstance()}. 045 */ 046 public void setAspectBeanName(String aspectBeanName) { 047 this.aspectBeanName = aspectBeanName; 048 } 049 050 @Override 051 public void setBeanFactory(BeanFactory beanFactory) { 052 this.beanFactory = beanFactory; 053 Assert.notNull(this.aspectBeanName, "'aspectBeanName' is required"); 054 } 055 056 057 /** 058 * Look up the aspect bean from the {@link BeanFactory} and returns it. 059 * @see #setAspectBeanName 060 */ 061 @Override 062 public Object getAspectInstance() { 063 return this.beanFactory.getBean(this.aspectBeanName); 064 } 065 066 @Override 067 public ClassLoader getAspectClassLoader() { 068 if (this.beanFactory instanceof ConfigurableBeanFactory) { 069 return ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader(); 070 } 071 else { 072 return ClassUtils.getDefaultClassLoader(); 073 } 074 } 075 076 @Override 077 public int getOrder() { 078 if (this.beanFactory.isSingleton(this.aspectBeanName) && 079 this.beanFactory.isTypeMatch(this.aspectBeanName, Ordered.class)) { 080 return ((Ordered) this.beanFactory.getBean(this.aspectBeanName)).getOrder(); 081 } 082 return Ordered.LOWEST_PRECEDENCE; 083 } 084 085}