Struts2容器之Container与ContainerImpl深入剖析及其Struts2依赖注入的原理剖析

本文深入探讨了容器概念及其在依赖注入中的作用,解释了构造函数、方法和属性的关联方式,强调了不可变性原则。通过实例展示了如何创建和注入对象,同时提供了容器源码预览,帮助开发者掌握这一核心技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Container容器概念:

依赖项注入的构造函数、方法和属性的关联。不可变。

注入方法或者构造函数的时候,你可以另外关联其参数和指定依赖的名称。当一个参数没有注解,容器使用方法或构造方法去单独注解。

例如:

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) {
    ...
  }
}

创建和注入Foo实例

Container c = ...;
Foo foo = c.inject(Foo.class);

Container容器源码预览

public interface Container extends Serializable {

  /**
   * Default dependency name.
   */
  String DEFAULT_NAME = "default";

  /**
   * Injects dependencies into the fields and methods of an existing object.
   */
  void inject(Object o);

  /**
   * Creates and injects a new instance of type {@code implementation}.
   */
  <T> T inject(Class<T> implementation);

  /**
   * Gets an instance of the given dependency which was declared in
   * {@link com.opensymphony.xwork2.inject.ContainerBuilder}.
   */
  <T> T getInstance(Class<T> type, String name);

  /**
   * Convenience method. Equivalent to {@code getInstance(type,
   * DEFAULT_NAME)}.
   */
  <T> T getInstance(Class<T> type);
  
  /**
   * Gets a set of all registered names for the given type
   * @param type The instance type
   * @return A set of registered names or empty set if no instances are registered for that type
   */
  Set<String> getInstanceNames(Class<?> type);

  /**
   * Sets the scope strategy for the current thread.
   */
  void setScopeStrategy(Scope.Strategy scopeStrategy);

  /**
   * Removes the scope strategy for the current thread.
   */
  void removeScopeStrategy();
}

还有很多,待续,,,,,,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值