1 /*
2  * Copyright 2008-2020 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.springframework.data.jpa.domain.support;
17
18 import static org.springframework.data.jpa.util.BeanDefinitionUtils.*;
19 import static org.springframework.util.StringUtils.*;
20
21 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
22 import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect;
23 import org.springframework.beans.factory.config.BeanDefinition;
24 import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
25 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
26
27 /**
28  * {@link BeanFactoryPostProcessor} that ensures that the {@link AnnotationBeanConfigurerAspect} aspect is up and
29  * running <em>before</em> the {@link javax.persistence.EntityManagerFactory} gets created as this already instantiates
30  * entity listeners and we need to get injection into {@link org.springframework.beans.factory.annotation.Configurable}
31  * to work in them.
32  *
33  * @author Oliver Gierke
34  * @author Thomas Darimont
35  */

36 public class AuditingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
37
38     public static final String BEAN_CONFIGURER_ASPECT_BEAN_NAME = "org.springframework.context.config.internalBeanConfigurerAspect";
39
40     /*
41      * (non-Javadoc)
42      * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
43      */

44     @Override
45     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
46
47         try {
48             getBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME, beanFactory);
49         } catch (NoSuchBeanDefinitionException o_O) {
50             throw new IllegalStateException(
51                     "Invalid auditing setup! Make sure you've used @EnableJpaAuditing or <jpa:auditing /> correctly!", o_O);
52         }
53
54         for (String beanName : getEntityManagerFactoryBeanNames(beanFactory)) {
55             BeanDefinition definition = getBeanDefinition(beanName, beanFactory);
56             definition.setDependsOn(addStringToArray(definition.getDependsOn(), BEAN_CONFIGURER_ASPECT_BEAN_NAME));
57         }
58     }
59 }
60