Spring-1 helloworld
来源:互联网 发布:fifaol3数据库app 编辑:程序博客网 时间:2024/06/06 00:17
毕业设计用了点spring的皮毛,几个月过去又给忘记了,现在想重新捡起来,想翻翻记录发现一条也没有,很后悔。
现在算是重新来一遍吧,希望自己可以坚持下去。
本来是想学学springMVC,一看教程,springMVC基于Spring, 如果Spring啥也不知道,估计也学不下去,于是又翻出来佟刚的视频看看。
工程结构:
1.建立一个普通java project
2.工程目录下建lib,放入jar(下面四个是必须的),并 build path
3.创建包com.csu.hello
4.在hello包下创建类:helloworld:
package com.csu.hello;public class helloworld { String name; public helloworld() { System.out.println("constructor......"); } public void setName(String name) { System.out.println("set name....."+name); this.name=name; } public void greet() { System.out.println("hello:"+this.name); }}
5.在hello包下创建Main类:
package com.csu.hello;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { // TODO Auto-generated method stub 1.helloworld实例 helloworld h1=new helloworld(); 2.设置属性值 h1.setName("Jerry"); 3.调用实例方法 h1.greet(); }}
以上步骤还跟spring没有一毛钱关系,一切都是传统做法,现在,用上IOC容器来达到一样的效果:
首先,在src下新建一个applicationContext.xml来写bean配置:
<?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.csu.hello.helloworld"> <!--配置 属性--> <property name="name" value="Jerry"></property></bean></beans>
然后改了Main:
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub /*1.helloworld实例 helloworld h1=new helloworld(); 2.设置属性值 h1.setName("Jerry"); 3.调用实例方法 h1.greet();*/ //1.获取IOC容器 AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); //2.获取bean实例 helloworld myHello=(helloworld) ctx.getBean("helloWorld"); //3.调用实例方法 myHello.greet(); }
运行结果一直,控制台打印出:hello Jerry
可以看到,用上Spring 的 IOC之后,我们想获得一个完整bean实例,不用自己new了,也不用自己调用set方法来设置属性,只要我们在xml里面把模子()做好之后,获取IOC容器,调用getBean(“beanid”)方法即可。
这样做的好处,首先,是便于管理所有实例,其次,如果修改某个实例的属性,只需要改xml 的property即可,而不需要进入程序改动。
0 0
- spring-1:Spring helloWorld
- 1、Spring之HelloWorld
- spring(1) helloworld
- java spring(1) HelloWorld
- Spring-1 helloworld
- Spring In Action (1) -- HelloWorld
- Spring(1)--初识Spring之HelloWorld
- Spring helloworld
- spring helloworld
- spring helloworld
- Spring -- HelloWorld
- spring helloworld
- Spring HelloWorld
- Spring--HelloWorld
- spring HelloWorld!
- spring-HelloWorld
- spring helloworld
- Spring-HelloWorld
- spark源码阅读笔记Dataset(二)Dataset中Actions、function、transformations
- 自己写逻辑回归 logistic regression
- C#对象间的协作和信息交换(五)利用委托(Delegate)广播消息
- 关于 java jdk的配置测试
- Redis 主从复制
- Spring-1 helloworld
- Android集成极光推送 的异常
- Windows下使用AndroidStudio+ReactNative开发Android应用
- 排序算法之——计数排序(Java实现)
- TCP---三次握手和四次挥手
- nodejs 文件操作
- UE4-碰撞事件:开关门蓝图类实现提升篇
- cuckoo的配置以及启动场景问题分析
- 聊聊HTTPS和SSL/TLS协议