Spring的依赖注入
spring框架为我们提供了三种注入方式,分别是set注入,构造方法注入,接口注入。
下面具体介绍set注入
set注入
采用属性的set方法进行初始化,就成为set注入
package com.bzu.zhu.Spring;
public class HellWord {
/**
* @param args
*/
private String name;
public void setName(String name) {
System.out.println("setname"+name);
this.name = name;
}
}
我们只需要提供属性的set方法,然后去属性文件中去配置好让框架能够找到applicationContext.xml文件的beans标签。标签beans中添加bean标签, 指定id,class值,id值不做要求,class值为对象所在的完整路径。bean标签再添加property 标签,要求,name值与User类中对应的属性名称一致。value值就是我们要给User类中的username属性赋的值。
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:util="http://http://www.springframework.org/schema/util"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd"
>
<!-- 配置Bean -->
<bean id="hellWord" class="com.bzu.zhu.Spring.HellWord">
<property name="name" value="zhu"></property>
</bean>
</beans>
然后在Main中测试,建立一个测试类
<span style="font-size:18px;">package com.bzu.zhu.Spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
<span style="color:#ff0000;"><strong>//1.创建Spring的Ioc容器对象</strong></span>
ApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
<strong><span style="color:#ff0000;">//2。从Ioc容器中获取bean对象</span></strong>
HellWord hellword=(HellWord) ctx.getBean("hellWord");
<span style="color:#33cc00;"><strong>//第二种方法:HellWord hellword=ctx.getBean(HellWord.class);</strong></span>
System.out.println(hellword);<span style="color:#ff0000;"><strong> //打印输出</strong></span>
}
}</span>
输出结果
setname zhu
com.bzu.zhu.Spring.HellWord@81b1fb