第一个Spring小程序
来源:互联网 发布:优化企业家发展环境 编辑:程序博客网 时间:2024/06/05 08:20
(1)添加5个jar包到类路径下
(2)在类路径下创建bean 配置文件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-4.0.xsd"></beans>
(3)不使用Spring框架
public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void hello(){ System.out.println("hello:"+name); }}
public class Main { public static void main(String[] args) { //通过new创建对象 HelloWorld hello=new HelloWorld(); //为对象的属性设置值 hello.setName("Spring"); //使用对象,调用对象的方法 hello.hello(); }}
在不使用Spring框架时,需要自己去new对象、为对象属性赋值,然后才使用对象。高耦合
下面来看一下怎么使用Spring框架吧
(4)使用Spring
使用Spring之后,对象的创建以及对象属性的赋值都交给了Spring框架。我们直接从Spring的IOC容器中取出装配好的对象,然后使用该对象。
配置文件:
<?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-4.0.xsd"> <bean id="hello" class="com.HelloWorld"> <property name="name" value="Spring"></property> </bean></beans>
public class Main { public static void main(String[] args) { //创建IOC容器对象 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); //从IOC容器获取bean实例 HelloWorld h=(HelloWorld) context.getBean("hello"); //调用bean的方法 h.hello(); }}
我们首先要做的就是实例化IOC容器对象,然后才能从容器中获取bean。
实例化IOC容器对象–>从容器中获取bean(已注入属性)–>使用bean
使用Spring框架,不需要自己创建对象,也不用自己为对象的属性赋值(这些工作交给IOC容器完成),却有相同的运行效果。Spring的IOC容器大大降低了耦合度
阅读全文
0 0
- 第一个Spring小程序
- Spring的第一个小程序
- 第一个小程序
- 第一个小程序
- 第一个Spring程序
- Spring第一个程序
- 第一个spring程序
- 第一个spring程序
- 第一个Spring程序
- Spring第一个程序
- Spring 第一个程序
- 第一个Spring程序
- 第一个Spring程序
- spring 框架搭建并创建第一个小程序
- 第一个spring小demo
- WindowsWorkFlow第一个小程序
- 第一个ajax小程序
- 第一个OpenGLES小程序
- 英语单词D
- Java面试题:寻找coder;
- hdu 6053 TrickGCD 【容斥&筛法|莫比乌斯】
- 数据库DML语言--合并语句
- jmeter如何将上一个请求的结果作为下一个请求的参数——使用正则提取器
- 第一个Spring小程序
- 对协程的理解
- SaltStack连接Linux&Windows机器
- AndroidStudio下使用Lambda表达式
- 解决Oracle出现以0开头的小数,开头的0消失的问题
- mysql忘记root密码的解决办法
- thinkphp 事物
- JavaScript实现二级联动
- day07 重写Override super() object类等 有错请多多指教