Introduces a new interface to allow initialise beans at the end of setup

This commit is contained in:
Lukasz Lenart
2017-09-26 08:47:42 +02:00
parent 2acf0ab16e
commit 4dfc8a2d6a
2 changed files with 60 additions and 1 deletions
@@ -21,7 +21,12 @@
package com.opensymphony.xwork2.inject;
import java.lang.reflect.Member;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
@@ -42,6 +47,7 @@ public final class ContainerBuilder {
final Map<Key<?>, InternalFactory<?>> factories = new HashMap<>();
final List<InternalFactory<?>> singletonFactories = new ArrayList<>();
final List<InternalFactory<?>> initializableFactories = new ArrayList<>();
final List<Class<?>> staticInjections = new ArrayList<>();
boolean created;
boolean allowDuplicates = false;
@@ -95,6 +101,20 @@ public final class ContainerBuilder {
}
});
}
if (Initializable.class.isAssignableFrom(key.getType())) {
initializableFactories.add(
new InternalFactory<T>() {
public T create(InternalContext context) {
try {
context.setExternalContext(ExternalContext.newInstance(null, key, context.getContainerImpl()));
return scopedFactory.create(context);
} finally {
context.setExternalContext(null);
}
}
}
);
}
return this;
}
@@ -574,6 +594,16 @@ public final class ContainerBuilder {
}
});
}
container.callInContext(new ContainerImpl.ContextualCallable<Void>() {
public Void call(InternalContext context) {
for (InternalFactory<?> factory : initializableFactories) {
Initializable instance = (Initializable) factory.create(context);
instance.init();
}
return null;
}
});
container.injectStatics(staticInjections);
return container;
}
@@ -0,0 +1,29 @@
/*
* Copyright 2002-2006,2009 The Apache Software Foundation.
*
* 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
*
* http://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 com.opensymphony.xwork2.inject;
/**
* Beans marked with this interface will be always initialised
* after the internal DI mechanism will be created.
*
* It should be only used internally!
*/
public interface Initializable {
void init();
}