Spring的依赖注入

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值