Java自学之spring:初识

学习目的:使用spring获取一个对象,并打印名字

Part 1

新建一个Java project,命名为spring。

v2-77f93412bf97e5b580618888b3956eb2_b.jpg

Part 2

导入spring框架所需要的jar包。

在spring项目文件夹内新建一个lib文件夹,用来存放spring所需jar包。

v2-bbb419cc883e0e604249f022d544cfc3_b.jpg

右键项目:spring->properties->java build path->libaries->add external jars

v2-bc3af36251bd59a6158c4af00318dd43_b.jpg

Part 3

新建一个pojo类:Category

package cn.vaefun.pojo;

public class Category {
	
	private int id;
	private String name;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

Part 4

在src下新建一个application.xml

配置一个bean,名字为c,class完整类名为上面pojo类Category的完整类名,并配置其name属性的value为category 1。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="Index of /schema/aop"
    xmlns:tx="Index of /schema/tx"
    xmlns:context="Index of /schema/context"
    xsi:schemaLocation="
   Index of /schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   Index of /schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   Index of /schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   Index of /schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <bean name="c" class="cn.vaefun.pojo.Category">
        <property name="name" value="category 1" />
    </bean>
  
</beans>

Part 5

新建一个TestSpring类。

package cn.vaefun.test;

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

import cn.vaefun.pojo.Category;

public class TestSpring {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
		Category category = (Category)context.getBean("c");
		System.out.println(category.getName());
	}
}

Part 6

运行成功,通过spring获取到一个Category对象,并输出其name:category 1,学习目的完成。

v2-cf145894c6712d7aa5509b3d64757fdd_b.jpg

Part 7

总结(以获取对象方式为例)

传统的方式:
通过new 关键字主动创建一个对象
IOC方式:
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是 反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
打个比喻:
传统方式:相当于你自己去菜市场new 了一只鸡,不过是生鸡,要自己拔毛,去内脏,再上花椒,酱油,烤制,经过各种工序之后,才可以食用。
用 IOC:相当于去馆子(Spring)点了一只鸡,交到你手上的时候,已经五味俱全,你就只管吃就行了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值