Spring 关于依赖注入的基本用法

在建立好一个基本的maven project 之后,导入基本的spring jar包,下面就可以进行基本的使用了。

1.首先,和平时一样定义一个类
例如:

/**
 * 定义一个类
 * @author Administrator
 *
 */
public class Person {

	public String name = "";
	
	public String getName() {
		return name;
	}

	//public void setName(String name) {
	//	this.name = name;
//}

}

2.在src/main/resource 下建立Beans.xml 文件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="person"
        class="com.shinion.basic.helloworld.Person">
    </bean>
  
</beans>

文件内容中,重要的是bean标记里面,id代表名字,也可以起其他自定义的名字,比如"aaa"都可以

3.调用:

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
			Person person =null;
			person = (Person)context.getBean("person");
			if(person!= null) {
				person.name = "aaa";
				System.out.println(person.getName());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

在需要使用的方法中,开始调用,我这里用的是一个测试类的主函数,调用步骤主要是两步,第一,定义context,第二,contex.getbean()方法。获得对象后,即和平时一样使用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值