【spring教程之一】创建一个最简单的spring例子

来源:互联网 发布:南航 java岗位 编辑:程序博客网 时间:2024/05/17 23:14

1、首先spring的主要思想,就是依赖注入。简单来说,就是不需要手动new对象,而这些对象由spring容器统一进行管理。


2、例子结构


如上图所示,采用的是maven工程。


2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>SpringExample001</groupId>  <artifactId>SpringExample001</artifactId>  <version>0.0.1-SNAPSHOT</version>    <dependencies>     <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-context</artifactId>         <version>3.2.5.RELEASE</version>     </dependency> </dependencies></project>

3、spring.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"             xmlns:context="http://www.springframework.org/schema/context"             xmlns:aop="http://www.springframework.org/schema/aop"             xmlns:tx="http://www.springframework.org/schema/tx"             xsi:schemaLocation="http://www.springframework.org/schema/beans                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                     http://www.springframework.org/schema/context                     http://www.springframework.org/schema/context/spring-context-3.0.xsd                     http://www.springframework.org/schema/aop                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd                     http://www.springframework.org/schema/tx                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  <bean id="do" class="com.test.pro.Do"/></beans>

4、Do.java

package com.test.pro;public class Do {public void speaking(){System.out.println("speaking.......");}}

5、测试类

package com.test.pro;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");Do did=(Do)ctx.getBean("do");did.speaking();}}


6、输出



7、分析

我们可以看到,在核心的spring配置文件中的spring.xml中只有一句话:<bean id="do" class="com.test.pro.Do"/>,这句话指明的是有一个bean文件,名称为do,其类的地址是com.test.pro.Do。

然后就是我们的测试类里面的一段话:

ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
Do did=(Do)ctx.getBean("do");
did.speaking();

这里表示声明一个上下文类,这个上下文类装载了配置文件,注意,如果这里不是采用maven工程的话,一定要注意spring.xml的相对地址,如果实在不确定相对地址是什么,可以采用绝对地址的方式,例如:

ApplicationContext ctx=new ClassPathXmlApplicationContext("file:H:/spring.xml");

然后就是利用上下文对象来获得在配置文件中声明过的bean的示例,并且可以直接调用。

那么这个bean文件是什么时候实例化的,如果bean的scope是prototype的,则该Bean的实例化是在第一次使用该Bean的时候进行实例化 ,可以参考这篇文章:http://www.iteye.com/problems/93479


0 0
原创粉丝点击