Spring简单入门

来源:互联网 发布:52kkm软件下载 编辑:程序博客网 时间:2024/06/05 10:08

    最近开始入坑Java EE中的Spring,这里记录一下使用Spring的第一个demo的步骤:

    1. 开发IDE使用Eclipse For Jave EE developer, 构建工具使用maven,JDK版本为1.8。新建一个maven的项目,在pom.xml文件增加对spring framework的依赖(这里我的eclipse没有安装spring ide插件,直接使用maven的依赖):

   

    2. 新增一个bean:

package cn.linjk.testspring;public class HelloBean {private String hello;public String getHello() {return hello;}public void setHello(String hello) {this.hello = hello;}}

    3. 新增bean.xml文件(存放在路径"src/main/java"下):

<?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="helloBean" class="cn.linjk.testspring.HelloBean">          <property name="hello" value="test_spring"></property>      </bean>  </beans>  
      这里有一个bean节点,id是提供外部调用,class对应类名加包名,然后再配置它的属性及其对应值。
   

    4. 测试代码:

package cn.linjk.testspring;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class App {public static void main(String[] args) {        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");                  HelloBean hello = (HelloBean) ctx.getBean("helloBean");          System.out.println(hello.getHello());                ctx.close();}}

      这里使用AbstractApplicationContext加载资源文件,XmlBeanFactory已经弃用了,使用它,写法类似这样:

BeanFactory bf = new XmlBeanFactory(new ClassPathResource("bean.xml"));

 HelloBean bean = (HelloBean)bf.getBean("helloBean");

System.out.println(hello.getHello());

如下:


注意:“ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");”不建议,这种写法占内存,耗资源,如果代码需要连接数据库,很容易造成系统运行缓慢。


这里,Spring框架帮我们做了如下几件事:

A. 读取配置文件bean.xml

B. 根据bean.xml中的配置找到对应的类的配置,并实例化

C. 调用实例化后的实例


核心类:

1. DefaultListableBeanFactory(XmlBeanFactory继承自该类) 路径: org.springframework.beans.factory.support.DefaultListableBeanFactory,

    DefaultListableBeanFactory是整个bean加载的核心部分,是Spring注册及加载bean的默认实现,

2. N/A.


 5. 运行结果如下: