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