此内容没有您所选择的语言版本。

Chapter 7. Advanced Dependency Injection and IoC


Today, Dependency injection (DI), also called Inversion of Control (IoC), lies at the core of many frameworks that embrace the notion of a container or a component model. Component models were discussed in a previous chapter. JBoss JMX kernel, the precursor to the Microcontainer, provided only lightweight DI/IoC support, primarily due to the limitations of accessing MBeans through the MBeans server. However with the new POJO-based component model, several new and interesting features are available.
This chapter shows how you can apply different DI concepts with the help of the JBoss Microcontainer. These concepts will be expressed via XML code, but you can also apply most of these features using annotations.

7.1. Value Factory

A value factory is a bean which has one or more methods devoted to generating values for you. See Example 7.1, “Value Factory”.

Example 7.1. Value Factory

<bean name="Binding" class="org.jboss.demos.ioc.vf.PortBindingManager">
  <constructor>
    <parameter>
      <map keyClass="java.lang.String" valueClass="java.lang.Integer">
	<entry>
	  <key>http</key>
	  <value>80</value>
	</entry>
	<entry>
	  <key>ssh</key>
	  <value>22</value>
	</entry>
      </map>
    </parameter>
  </constructor>
</bean>
<bean name="PortsConfig" class="org.jboss.demos.ioc.vf.PortsConfig">
  <property name="http"><value-factory bean="Binding" method="getPort" parameter="http"/></property>
  <property name="ssh"><value-factory bean="Binding" method="getPort" parameter="ssh"/></property>
  <property name="ftp">
    <value-factory bean="Binding" method="getPort">
      <parameter>ftp</parameter>
      <parameter>21</parameter>
    </value-factory>
  </property>
  <property name="mail">
    <value-factory bean="Binding" method="getPort">
      <parameter>mail</parameter>
      <parameter>25</parameter>
    </value-factory>
  </property>
</bean>
			
			
			

Copy to Clipboard Toggle word wrap
Example 7.2, “PortsConfig” shows how the PortsConfig bean uses Binding bean to get its values via the getPort method invocation.

Example 7.2. PortsConfig

public class PortBindingManager {
    private Map<String, Integer> bindings;
    public PortBindingManager(Map<String, Integer> bindings)
    {
	this.bindings = bindings;
    }
    public Integer getPort(String key)
    {
	return getPort(key, null);
    }
    public Integer getPort(String key, Integer defaultValue)
    {
	if (bindings == null)
	    return defaultValue;
	Integer value = bindings.get(key);
	if (value != null)
	    return value;
	if (defaultValue != null)
	    bindings.put(key, defaultValue);
	return defaultValue;
    }
}
			
			
			

Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat