Spring学习之IOC控制反转(一.属性~构造方法注入)

(一)IOC:控制反转,简单解释为正常使用对象时我们需要进行对其创建,而现在我们将创建对象的任务交给Spring完成,由IOC容器完成。
(二)代码测试:

先贴上spring一些jar包的功能:
在这里插入图片描述
本项目中使用jar包如下:
在这里插入图片描述
首先创建一个User类:

package com.entity;

public class People {

	private String name;
	private int age;
	
	public People() {
		super();
		// TODO Auto-generated constructor stub
	}

	public People(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	
	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "People [name=" + name + ", age=" + age + "]";
	}
	
	
}

在src目录下写一个applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">

    <!-- 将user对象交给spring进行创建 -->
    <!-- 
        name:调用时用的名字
        class:路径
    -->
    
       <bean id="people1" class="com.entity.People">
       		<property name="name" value="小可爱"></property>
       		<property name="age" value="123"></property>
       </bean>
        
       <bean id="people2" class="com.entity.People">
       		<constructor-arg type="int" value="2"></constructor-arg>
       		<constructor-arg type="String" value="小帅气"></constructor-arg>
       </bean>
       
       <bean id="people3" class="com.entity.People">
       		<constructor-arg index="0" value="小奇怪"></constructor-arg>
       		<constructor-arg index="1" value="56"></constructor-arg>
       </bean>
       
</beans>

写测试类:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.entity.People;

public class TestMethod {

	public static void main(String[] args) {
		
		//创建spring容器对象
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		
		//获取spring创建的user对象
		People p1=(People)ac.getBean("people1");
		People p2=(People)ac.getBean("people2");
		People p3=(People)ac.getBean("people3");
		
		System.out.println(p1);
		System.out.println(p2);
		System.out.println(p3);
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值