001/*
002 * Copyright 2002-2018 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.web.socket.handler;
018
019import org.springframework.beans.BeanUtils;
020import org.springframework.beans.factory.BeanFactory;
021import org.springframework.beans.factory.BeanFactoryAware;
022import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
023import org.springframework.lang.Nullable;
024import org.springframework.util.Assert;
025
026/**
027 * Instantiates a target handler through a Spring {@link BeanFactory} and also provides
028 * an equivalent destroy method. Mainly for internal use to assist with initializing and
029 * destroying handlers with per-connection lifecycle.
030 *
031 * @author Rossen Stoyanchev
032 * @since 4.0
033 * @param <T> the handler type
034 */
035public class BeanCreatingHandlerProvider<T> implements BeanFactoryAware {
036
037        private final Class<? extends T> handlerType;
038
039        @Nullable
040        private AutowireCapableBeanFactory beanFactory;
041
042
043        public BeanCreatingHandlerProvider(Class<? extends T> handlerType) {
044                Assert.notNull(handlerType, "handlerType must not be null");
045                this.handlerType = handlerType;
046        }
047
048
049        @Override
050        public void setBeanFactory(BeanFactory beanFactory) {
051                if (beanFactory instanceof AutowireCapableBeanFactory) {
052                        this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
053                }
054        }
055
056        public void destroy(T handler) {
057                if (this.beanFactory != null) {
058                        this.beanFactory.destroyBean(handler);
059                }
060        }
061
062
063        public Class<? extends T> getHandlerType() {
064                return this.handlerType;
065        }
066
067        public T getHandler() {
068                if (this.beanFactory != null) {
069                        return this.beanFactory.createBean(this.handlerType);
070                }
071                else {
072                        return BeanUtils.instantiateClass(this.handlerType);
073                }
074        }
075
076        @Override
077        public String toString() {
078                return "BeanCreatingHandlerProvider[handlerType=" + this.handlerType + "]";
079        }
080
081}