|
| 1 | +/* |
| 2 | + * Copyright 2002-2022 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 | + |
| 17 | +package org.springframework.context.generator; |
| 18 | + |
| 19 | +import java.util.ArrayList; |
| 20 | +import java.util.Comparator; |
| 21 | +import java.util.List; |
| 22 | +import java.util.Objects; |
| 23 | +import java.util.function.BiPredicate; |
| 24 | +import java.util.stream.Stream; |
| 25 | + |
| 26 | +import javax.lang.model.element.Modifier; |
| 27 | + |
| 28 | +import org.apache.commons.logging.Log; |
| 29 | +import org.apache.commons.logging.LogFactory; |
| 30 | + |
| 31 | +import org.springframework.aot.generator.GeneratedType; |
| 32 | +import org.springframework.aot.generator.GeneratedTypeContext; |
| 33 | +import org.springframework.beans.factory.BeanFactory; |
| 34 | +import org.springframework.beans.factory.config.BeanDefinition; |
| 35 | +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; |
| 36 | +import org.springframework.beans.factory.generator.AotContributingBeanFactoryPostProcessor; |
| 37 | +import org.springframework.beans.factory.generator.AotContributingBeanPostProcessor; |
| 38 | +import org.springframework.beans.factory.generator.BeanDefinitionsContribution; |
| 39 | +import org.springframework.beans.factory.generator.BeanFactoryContribution; |
| 40 | +import org.springframework.beans.factory.support.DefaultListableBeanFactory; |
| 41 | +import org.springframework.context.ApplicationContext; |
| 42 | +import org.springframework.context.ApplicationContextInitializer; |
| 43 | +import org.springframework.context.support.GenericApplicationContext; |
| 44 | +import org.springframework.core.OrderComparator; |
| 45 | +import org.springframework.javapoet.CodeBlock; |
| 46 | +import org.springframework.javapoet.MethodSpec; |
| 47 | +import org.springframework.javapoet.ParameterizedTypeName; |
| 48 | + |
| 49 | +/** |
| 50 | + * Process an {@link ApplicationContext} and its {@link BeanFactory} to generate |
| 51 | + * code that represents the state of the bean factory, as well as the necessary |
| 52 | + * hints that can be used at runtime in a constrained environment. |
| 53 | + * |
| 54 | + * @author Stephane Nicoll |
| 55 | + * @since 6.0 |
| 56 | + */ |
| 57 | +public class ApplicationContextAotGenerator { |
| 58 | + |
| 59 | + private static final Log logger = LogFactory.getLog(ApplicationContextAotGenerator.class); |
| 60 | + |
| 61 | + /** |
| 62 | + * Refresh the specified {@link GenericApplicationContext} and generate the |
| 63 | + * necessary code to restore the state of its {@link BeanFactory}, using the |
| 64 | + * specified {@link GeneratedTypeContext}. |
| 65 | + * @param applicationContext the application context to handle |
| 66 | + * @param generationContext the generation context to use |
| 67 | + */ |
| 68 | + public void generateApplicationContext(GenericApplicationContext applicationContext, |
| 69 | + GeneratedTypeContext generationContext) { |
| 70 | + applicationContext.refreshForAotProcessing(); |
| 71 | + |
| 72 | + DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); |
| 73 | + List<BeanFactoryContribution> contributions = resolveBeanFactoryContributions(beanFactory); |
| 74 | + |
| 75 | + filterBeanFactory(contributions, beanFactory); |
| 76 | + ApplicationContextInitialization applicationContextInitialization = new ApplicationContextInitialization(generationContext); |
| 77 | + applyContributions(contributions, applicationContextInitialization); |
| 78 | + |
| 79 | + GeneratedType mainGeneratedType = generationContext.getMainGeneratedType(); |
| 80 | + mainGeneratedType.customizeType(type -> type.addSuperinterface(ParameterizedTypeName.get( |
| 81 | + ApplicationContextInitializer.class, GenericApplicationContext.class))); |
| 82 | + mainGeneratedType.addMethod(initializeMethod(applicationContextInitialization.toCodeBlock())); |
| 83 | + } |
| 84 | + |
| 85 | + private MethodSpec.Builder initializeMethod(CodeBlock methodBody) { |
| 86 | + MethodSpec.Builder method = MethodSpec.methodBuilder("initialize").addModifiers(Modifier.PUBLIC) |
| 87 | + .addParameter(GenericApplicationContext.class, "context").addAnnotation(Override.class); |
| 88 | + method.addCode(methodBody); |
| 89 | + return method; |
| 90 | + } |
| 91 | + |
| 92 | + private void filterBeanFactory(List<BeanFactoryContribution> contributions, DefaultListableBeanFactory beanFactory) { |
| 93 | + BiPredicate<String, BeanDefinition> filter = Stream.concat(Stream.of(aotContributingExcludeFilter()), |
| 94 | + contributions.stream().map(BeanFactoryContribution::getBeanDefinitionExcludeFilter)) |
| 95 | + .filter(Objects::nonNull).reduce((n, d) -> false, BiPredicate::or); |
| 96 | + for (String beanName : beanFactory.getBeanDefinitionNames()) { |
| 97 | + BeanDefinition bd = beanFactory.getMergedBeanDefinition(beanName); |
| 98 | + if (filter.test(beanName, bd)) { |
| 99 | + if (logger.isDebugEnabled()) { |
| 100 | + logger.debug("Filtering out bean with name" + beanName + ": " + bd); |
| 101 | + } |
| 102 | + beanFactory.removeBeanDefinition(beanName); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // TODO: is this right? |
| 108 | + private BiPredicate<String, BeanDefinition> aotContributingExcludeFilter() { |
| 109 | + return (beanName, beanDefinition) -> { |
| 110 | + Class<?> type = beanDefinition.getResolvableType().toClass(); |
| 111 | + return AotContributingBeanFactoryPostProcessor.class.isAssignableFrom(type) || |
| 112 | + AotContributingBeanPostProcessor.class.isAssignableFrom(type); |
| 113 | + }; |
| 114 | + } |
| 115 | + |
| 116 | + |
| 117 | + private void applyContributions(List<BeanFactoryContribution> contributions, |
| 118 | + ApplicationContextInitialization initialization) { |
| 119 | + for (BeanFactoryContribution contribution : contributions) { |
| 120 | + contribution.applyTo(initialization); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + /** |
| 125 | + * Resolve the {@link BeanFactoryContribution} available in the specified |
| 126 | + * bean factory. Infrastructure is contributed first, and bean definitions |
| 127 | + * registration last. |
| 128 | + * @param beanFactory the bean factory to process |
| 129 | + * @return the contribution to apply |
| 130 | + * @see InfrastructureContribution |
| 131 | + * @see BeanDefinitionsContribution |
| 132 | + */ |
| 133 | + private List<BeanFactoryContribution> resolveBeanFactoryContributions(DefaultListableBeanFactory beanFactory) { |
| 134 | + List<BeanFactoryContribution> contributions = new ArrayList<>(); |
| 135 | + contributions.add(new InfrastructureContribution()); |
| 136 | + List<AotContributingBeanFactoryPostProcessor> postProcessors = getAotContributingBeanFactoryPostProcessors(beanFactory); |
| 137 | + for (AotContributingBeanFactoryPostProcessor postProcessor : postProcessors) { |
| 138 | + BeanFactoryContribution contribution = postProcessor.contribute(beanFactory); |
| 139 | + if (contribution != null) { |
| 140 | + contributions.add(contribution); |
| 141 | + } |
| 142 | + } |
| 143 | + contributions.add(new BeanDefinitionsContribution(beanFactory)); |
| 144 | + return contributions; |
| 145 | + } |
| 146 | + |
| 147 | + private static List<AotContributingBeanFactoryPostProcessor> getAotContributingBeanFactoryPostProcessors(DefaultListableBeanFactory beanFactory) { |
| 148 | + String[] postProcessorNames = beanFactory.getBeanNamesForType(AotContributingBeanFactoryPostProcessor.class, true, false); |
| 149 | + List<AotContributingBeanFactoryPostProcessor> postProcessors = new ArrayList<>(); |
| 150 | + for (String ppName : postProcessorNames) { |
| 151 | + postProcessors.add(beanFactory.getBean(ppName, AotContributingBeanFactoryPostProcessor.class)); |
| 152 | + } |
| 153 | + sortPostProcessors(postProcessors, beanFactory); |
| 154 | + return postProcessors; |
| 155 | + } |
| 156 | + |
| 157 | + private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) { |
| 158 | + // Nothing to sort? |
| 159 | + if (postProcessors.size() <= 1) { |
| 160 | + return; |
| 161 | + } |
| 162 | + Comparator<Object> comparatorToUse = null; |
| 163 | + if (beanFactory instanceof DefaultListableBeanFactory) { |
| 164 | + comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator(); |
| 165 | + } |
| 166 | + if (comparatorToUse == null) { |
| 167 | + comparatorToUse = OrderComparator.INSTANCE; |
| 168 | + } |
| 169 | + postProcessors.sort(comparatorToUse); |
| 170 | + } |
| 171 | + |
| 172 | +} |
0 commit comments