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.beans.factory.config;
018
019import org.springframework.beans.factory.FactoryBean;
020import org.springframework.beans.factory.FactoryBeanNotInitializedException;
021import org.springframework.lang.Nullable;
022
023/**
024 * {@link FactoryBean} which returns a value which is the result of a static or instance
025 * method invocation. For most use cases it is better to just use the container's
026 * built-in factory method support for the same purpose, since that is smarter at
027 * converting arguments. This factory bean is still useful though when you need to
028 * call a method which doesn't return any value (for example, a static class method
029 * to force some sort of initialization to happen). This use case is not supported
030 * by factory methods, since a return value is needed to obtain the bean instance.
031 *
032 * <p>Note that as it is expected to be used mostly for accessing factory methods,
033 * this factory by default operates in a <b>singleton</b> fashion. The first request
034 * to {@link #getObject} by the owning bean factory will cause a method invocation,
035 * whose return value will be cached for subsequent requests. An internal
036 * {@link #setSingleton singleton} property may be set to "false", to cause this
037 * factory to invoke the target method each time it is asked for an object.
038 *
039 * <p><b>NOTE: If your target method does not produce a result to expose, consider
040 * {@link MethodInvokingBean} instead, which avoids the type determination and
041 * lifecycle limitations that this {@link MethodInvokingFactoryBean} comes with.</b>
042 *
043 * <p>This invoker supports any kind of target method. A static method may be specified
044 * by setting the {@link #setTargetMethod targetMethod} property to a String representing
045 * the static method name, with {@link #setTargetClass targetClass} specifying the Class
046 * that the static method is defined on. Alternatively, a target instance method may be
047 * specified, by setting the {@link #setTargetObject targetObject} property as the target
048 * object, and the {@link #setTargetMethod targetMethod} property as the name of the
049 * method to call on that target object. Arguments for the method invocation may be
050 * specified by setting the {@link #setArguments arguments} property.
051 *
052 * <p>This class depends on {@link #afterPropertiesSet()} being called once
053 * all properties have been set, as per the InitializingBean contract.
054 *
055 * <p>An example (in an XML based bean factory definition) of a bean definition
056 * which uses this class to call a static factory method:
057 *
058 * <pre class="code">
059 * &lt;bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
060 *   &lt;property name="staticMethod" value="com.whatever.MyClassFactory.getInstance"/>
061 * &lt;/bean></pre>
062 *
063 * <p>An example of calling a static method then an instance method to get at a
064 * Java system property. Somewhat verbose, but it works.
065 *
066 * <pre class="code">
067 * &lt;bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
068 *   &lt;property name="targetClass" value="java.lang.System"/>
069 *   &lt;property name="targetMethod" value="getProperties"/>
070 * &lt;/bean>
071 *
072 * &lt;bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
073 *   &lt;property name="targetObject" ref="sysProps"/>
074 *   &lt;property name="targetMethod" value="getProperty"/>
075 *   &lt;property name="arguments" value="java.version"/>
076 * &lt;/bean></pre>
077 *
078 * @author Colin Sampaleanu
079 * @author Juergen Hoeller
080 * @since 21.11.2003
081 * @see MethodInvokingBean
082 * @see org.springframework.util.MethodInvoker
083 */
084public class MethodInvokingFactoryBean extends MethodInvokingBean implements FactoryBean<Object> {
085
086        private boolean singleton = true;
087
088        private boolean initialized = false;
089
090        /** Method call result in the singleton case. */
091        @Nullable
092        private Object singletonObject;
093
094
095        /**
096         * Set if a singleton should be created, or a new object on each
097         * {@link #getObject()} request otherwise. Default is "true".
098         */
099        public void setSingleton(boolean singleton) {
100                this.singleton = singleton;
101        }
102
103        @Override
104        public void afterPropertiesSet() throws Exception {
105                prepare();
106                if (this.singleton) {
107                        this.initialized = true;
108                        this.singletonObject = invokeWithTargetException();
109                }
110        }
111
112
113        /**
114         * Returns the same value each time if the singleton property is set
115         * to "true", otherwise returns the value returned from invoking the
116         * specified method on the fly.
117         */
118        @Override
119        @Nullable
120        public Object getObject() throws Exception {
121                if (this.singleton) {
122                        if (!this.initialized) {
123                                throw new FactoryBeanNotInitializedException();
124                        }
125                        // Singleton: return shared object.
126                        return this.singletonObject;
127                }
128                else {
129                        // Prototype: new object on each call.
130                        return invokeWithTargetException();
131                }
132        }
133
134        /**
135         * Return the type of object that this FactoryBean creates,
136         * or {@code null} if not known in advance.
137         */
138        @Override
139        public Class<?> getObjectType() {
140                if (!isPrepared()) {
141                        // Not fully initialized yet -> return null to indicate "not known yet".
142                        return null;
143                }
144                return getPreparedMethod().getReturnType();
145        }
146
147        @Override
148        public boolean isSingleton() {
149                return this.singleton;
150        }
151
152}