SpringBeanClassBasedListenerObjectCreator.java

/*
 * Copyright (C) 2012-2024 RRiBbit.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.rribbit.creation;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.rribbit.Listener;
import org.rribbit.ListenerObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * This {@link ListenerObjectCreator} creates {@link ListenerObject}s from classes. Users can pass in {@link Class}es or packagenames and this class will scan the {@link Class}es
 * and create {@link ListenerObject}s for the public methods that are annotated with {@link Listener}. Note that public methods inherited from superclasses and superinterfaces will also be
 * scanned. This means that users must take care not to scan a method twice, once as a method of a class and once as a method of a superclass, by passing a class/interface and its
 * superclass/superinterface separately to this {@link ListenerObjectCreator}.
 * <p />
 * Please note that in Java, method annotations are NOT inherited. This means that, if you override/implement a method in a subclass or subinterface, and the overriding/implementing method
 * does not have the annotation, then that method will not inherit it. If a class or interface just inherits a method, without overriding it, then the annotation WILL exist.
 * <p />
 * To get the actual {@link Object}s that the listeners run on, this will attempt to get a bean for a certain {@link Class} from the Spring Configuration.
 * When no suitable bean can be found, the {@link Class} will simply be ignored.
 * <p />
 * When the classnames and/or packagenames are set, the classes/packagenames are accumulated into {@link Collection}s, but actual processing of them will be done once the entire Spring
 * Configuration is initialized. This is because this class needs other Spring Beans from the configuration to initialize the {@link ListenerObject}s.
 * <p />
 * By default, subpackages of packages are not scanned. This can be changed by using the {@link #setScanSubpackages(boolean)} method.
 * <p />
 * NOTE: When using interface-based Spring Proxy's, you have to declare your {@link Listener} annotations on the interface-methods, not the class methods. RRiBbit does not even need to
 * know about the implementing classes, it will simply ask Spring for a bean that implements the interface that the method is declared in.
 *
 * @author G.J. Schouten
 *
 */
public class SpringBeanClassBasedListenerObjectCreator extends AbstractClassBasedListenerObjectCreator implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

	private static final Logger log = LoggerFactory.getLogger(SpringBeanClassBasedListenerObjectCreator.class);

	protected Collection<Class<?>> classesToBeProcessed;
	protected Collection<String> packageNamesToBeProcessed;
	protected Collection<Class<?>> classesToBeExcluded;
	protected boolean scanSubpackages;

	protected ApplicationContext applicationContext;

	/**
	 * Constructors of superclass are not copied, since that would make declaring a bean of this type in the Spring configuration quite verbose. Use the provided setters instead.
	 */
	public SpringBeanClassBasedListenerObjectCreator() {
		classesToBeProcessed = new CopyOnWriteArrayList<>();
		packageNamesToBeProcessed = new CopyOnWriteArrayList<>();
		classesToBeExcluded = new CopyOnWriteArrayList<>();
		scanSubpackages = false;
	}

	/**
	 * Set the classNames that are to be processed by calling {@link #addClass(Class)} once the Spring Configuration is initialized.
	 *
	 * @param classNames
	 */
	public void setClassNames(List<String> classNames) {

		for(String className : classNames) {
			try {
				classesToBeProcessed.add(Class.forName(className));
			} catch(Exception e) {
				throw new RuntimeException("Instantiation of Class object for class '" + className + "' failed", e);
			}
		}
	}

	/**
	 * Set the packageNames that are to be processed by calling {@link #addPackage(String, boolean)} once the Spring Configuration is initialized.
	 *
	 * @param packageNames
	 */
	public void setPackageNames(List<String> packageNames) {

		packageNamesToBeProcessed.addAll(packageNames);
	}

	/**
	 * Sets the classes that should be exluced when the packages set with {@link #setPackageNames(List)} are scanned.
	 *
	 * @param excludedClasses
	 */
	public void setExcludedClasses(Collection<Class<?>> excludedClasses) {

		classesToBeExcluded.addAll(excludedClasses);
	}

	/**
	 * Sets whether subpackages need to be scanned too. The default is false.
	 *
	 * @param scanSubpackages
	 */
	public void setScanSubpackages(boolean scanSubpackages) {
		this.scanSubpackages = scanSubpackages;
	}

	@Override
	protected Object getTargetObjectForClass(Class<?> clazz) {

		try {
			log.debug("Attempting to get bean of class '{}'", clazz.getName());
			return applicationContext.getBean(clazz);
		} catch(NoSuchBeanDefinitionException e) {
			log.debug("No suitable bean found, returning null");
			return null;
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	/**
	 * When the Spring Configuration is reloaded, all {@link ListenerObject}s contained in this {@link ListenerObjectCreator} are dropped, and new ones are created from the classNames
	 * and packageNames set in this bean. This means that if you added listeners to this object with one of the methods of one of the superclasses, such as {@link #addClass(Class)},
	 * {@link #addObject(Object)} or {@link #addPackage(String, boolean)}, all the {@link ListenerObject}s that resulted from those calls will no longer be there after this call.
	 * <p />
	 * This is by design. The reason for doing this is because a {@link ContextRefreshedEvent} represents a total refresh of all objects in the application, erasing previous state. If you
	 * do not want this, you can extend this class and override the three mentioned add* methods. Each of them must then add the {@link Class}es and packageNames it processes to the
	 * {@link Collection}s in this object, before calling super.
	 *
	 * @param contextRefreshedEvent
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

		if(contextRefreshedEvent.getApplicationContext().equals(applicationContext)) { //Only do this for this ApplicationContext, not for child contexts
			log.debug("Clearing existing ListenerObjects");
			listenerObjects.clear();

			log.debug("Adding original classes");
			for(Class<?> clazz : classesToBeProcessed) {
				this.addClass(clazz);
			}

			log.debug("Adding original classes to be excluded");
			for(Class<?> clazz : classesToBeExcluded) {
				this.excludeClass(clazz);
			}

			log.debug("Adding original packages");
			for(String packageName : packageNamesToBeProcessed) {
				this.addPackage(packageName, scanSubpackages);
			}
		}
	}
}