Container API
参考:http://struts.apache.org/2.1.2/struts2-core/apidocs/com/opensymphony/xwork2/inject/Container.html
public interface Container
extends Serializable
Injects dependencies into constructors, methods and fields annotated with Inject. Immutable.
// 当某个类的构造子、方法或者域(成员变量、方法参数)有声明@Inject,调用container.inject(某类名.class)就能够得到该类的实例,这个实例已初始化好、凡是有@Inject注释类的成员也已经有值,其值即是下面说的default implementation,而这个implementation是在ContainerBuilder构造container前通过工厂方法事先注入的。
ContainerBuilder API说明:
The combination of dependency type and name uniquely identifies a dependency mapping;you can use the same name for two different types.
也就是说每种type只对应一个default implementation.
// Immutable--不可变的。(没搞懂)
When injecting a method or constructor, you can additionally annotate its parameters with Inject and specify a dependency name. When a parameter has no annotation, the container uses the name from the method or constructor's Inject annotation respectively.
For example:
class Foo {
// Inject the int constant named "i".
@Inject("i") int i;
// Inject the default implementation of Bar and the String constant
// named "s".
@Inject Foo(Bar bar, @Inject("s") String s) {
...
}
// Inject the default implementation of Baz and the Bob implementation
// named "foo".
@Inject void initialize(Baz baz, @Inject("foo") Bob bob) {
...
}
// Inject the default implementation of Tee.
@Inject void setTee(Tee tee) {
...
}
}
// default implementation
To create and inject an instance of Foo:
Container c = ...;
Foo foo = c.inject(Foo.class);
ContainerBuilder API
参考:http://struts.apache.org/2.1.2/struts2-core/apidocs/com/opensymphony/xwork2/inject/ContainerBuilder.html
public final class ContainerBuilder
extends Object
Builds a dependency injection Container. The combination of dependency type and name uniquely identifies a dependency mapping; you can use the same name for two different types. Not safe for concurrent use.
Adds the following factories by default:
* Injects the current Container.
* Injects the Logger for the injected member's declaring class.
几个方法:
| factory (Class<T> type, String name, Class<? extends T> implementation) Maps an implementation class to a given dependency type and name. | |
| factory (Class<T> type, String name, Class<? extends T> implementation, Scope scope) Maps an implementation class to a given dependency type and name. |
| factory (Class<T> type, String name, Factory<? extends T> factory, Scope scope) Maps a factory to a given dependency type and name. |
实例