创建项目

使用maven创建项目,选择quickstart版本,这里还用不到web所以用这个就足够了

如果不使用maven,那就创建一个普通java工程.
导入jar包:
这是我使用的所有jar包集合,包括后面学习所使用的所有jar:
https://download.csdn.net/download/abc997995674/10418625
<https://download.csdn.net/download/abc997995674/10418625>

创建好工程后,引入依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context
</artifactId> <version>4.1.1.RELEASE</version> </dependency>
* 这里只是使用springIOC功能,所以引入spring-context依赖就可以了。 spring-context就是给 Spring

提供一个运行时的环境,用以保存各个对象的状态,其实就是spring容器,引入这个依赖会自动引入其所依赖的其他基础依赖,如spring-core和spring-bean等。


创建一个HelloWorld类
package com.spring.ioc; public class HelloWorld { private String name; public
void setName(String name){ this.name = name; } public void sayHello(){ System.
out.println("HellowWorld,我的名字是 : "+ name); } }
配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <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=
"helloWorld" class="com.spring.ioc.HelloWorld"> <property name="name" value=
"YellowStar"></property> </bean> </beans>
测试
package com.spring.ioc; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test1 { public static void main(String[] args) { //创建spring的IOC容器对象
//Application是spring中的接口
//ClassPathXmlApplicationContext,可以获取src下的applicationContext.xml文件
ApplicationContext ct =new ClassPathXmlApplicationContext(
"applicationContext.xml"); HelloWorld helloWorld = (HelloWorld) ct.getBean(
"helloWorld"); helloWorld.sayHello(); } }
输出结果



* 新建了一个HelloWorld类,里面有个属性name和setName方法
* 在配置文件applicationContext.xml中创建了HelloWorld类的bean,并且为其name属性赋了值: <property
name="name" value="YellowStar"></property>
还可以用这种方式赋值:
<property name="name"> <value>YellowStar</value> </property>
在测试类中:
首先创建spring上下文环境(spring容器)
ApplicationContext ctx = new
ClassPathXmlApplicationContext(“applicationContext.xml”);
然后从里面取出helloWorld这个bean:
HelloWorld helloWorld = (HelloWorld) ctx.getBean(“helloWorld”);

实际上spring容器就是一个map集合,里面放入了id和对象的键值对。

本系列参考视频教程: http://edu.51cto.com/course/1956.html
<http://edu.51cto.com/course/1956.html>

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信