spring之第一个spring程序
spring具体描述:
一、搭建spring开发环境 在eclipse中新建一个java项目,在项目中新建一个lib文件夹,并将以下spring需要的jar包放在lib文件夹下: 选中这五个包,点击鼠标右键,选择bulid path-->add to build path, 最终的项目目录如下: 在src下新建一个包,在包里面新建两个java文件。在src下新建一个Spring bean configure file类型的文件:applicationContext.xml 二、第一个spring程序 HelloWorld.java package com.gong.spring.beans; public class HelloWorld { public HelloWorld() { System.out.println("构造方法"); } private String name; void setName(String name) { this.name = name; } show() { System.out.println("姓名是:"+this.name); } } Main.java import org.springframework.context.ApplicationContext; org.springframework.context.support.ClassPathXmlApplicationContext; Main { static main(String[] args) { /* * 普通的java对象的创建 HelloWorld helloworld = new HelloWorld(); helloworld.setName("tom"); helloworld.show(); */ //通过spring创建的对象 1.创建spring的IOC容器对象 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); 2.从容器中获取Bean实例 HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); 3.调用方法 helloWorld.show(); } } 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 --> <bean id="helloWorld" class="com.gong.spring.beans.HelloWorld"> <property name="name" value="jack"></property> </bean> </beans> 使用spring管理java对象时需要注意的地方: 在applicationContext.xml中,id是标识该类的名称,class是具体的某一个类名。property 是类的属性标识,name代表属性名,value代表值。 在Main.java中,先创建IOC容器对象,然后获取Bean实例,getBean()中的名称就是applicationContext.xml中id的内容。 最后输出: 可以看到,该类的构造方法也会被调用。我们可以得出,通过spring获取对象的实例会调用该类的构造方法,并且为相应的属性赋予初始值。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |