版权声明:仅供学习交流使用 https://blog.csdn.net/drxRose/article/details/84930066
DI即Dependency injection.
实现依赖注入有两种方式,一个是基于有参构造器的方式,一个是基于setter方法的方式.
另可使用p和c的命名空间的编写方式替代,在xml配置文件中.其namespace的链接地址分别为:
http://www.springframework.org/schema/p和http://www.springframework.org/schema/c
在配置文件中的beans标签内,添加格式为`xmlns:p=""`和xmlns:c=""`.
方式 | 说明 | 使用的标签 |
构造器的方式 | 必须有有参构造器 | constructor-arg |
setter的方式 | 必须有相关属性的setter方法 | property |
说明,依赖解析的过程,官方参考文档原文件(4.3.20版本)
The container performs bean dependency resolution as follows:
- The ApplicationContext is created and initialized with configuration metadata that describes all
the beans. Configuration metadata can be specified via XML, Java code, or annotations - For each bean, its dependencies are expressed in the form of properties, constructor arguments, or
arguments to the static-factory method if you are using that instead of a normal constructor. These
dependencies are provided to the bean, when the bean is actually created. - Each property or constructor argument is an actual definition of the value to set, or a reference to
another bean in the container. - Each property or constructor argument which is a value is converted from its specified format to the
actual type of that property or constructor argument. By default Spring can convert a value supplied
in string format to all built-in types, such as int, long, String, boolean, etc.
依赖于String类的类对象
package siye;
public class Obj
{
String str;
public Obj()
{
}
public Obj(String str)
{// 有参构造器处理依赖
this.str = str;
}
public void setStr(String str)
{// setter方法处理依赖
this.str = str;
}
}
xml配置文件,文件名`config.xml`
<bean id="objOthers" class="java.lang.String">
<constructor-arg name="original" value="message"
type="java.lang.String" />
</bean>
<!--DI的方式:有参构造器 -->
<bean id="obj0" class="siye.Obj">
<constructor-arg index="0" ref="objOthers" />
</bean>
<!--DI的方式:setter方法 -->
<bean id="obj1" class="siye.Obj">
<property name="str">
<ref bean="objOthers" />
</property>
</bean>
测试类
package siye;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UnitTest
{
public static void main(String[] args)
{
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("classpath:/siye/config.xml");
Obj obj0 = context.getBean("obj0", Obj.class);
System.out.println(obj0.str);
Obj obj1 = context.getBean("obj1", Obj.class);
System.out.println(obj1.str);
context.close();
}
}