2. Spring简单例子

来源:互联网 发布:网络投保车险 编辑:程序博客网 时间:2024/06/07 03:09

说明

下面的示例可能会在以后文章中用到

Spring4说明

spring4支持javaSE 6 (jdk1.6.0_18)及以上版本,但建议使用java 7或8。

spring4还提供一些Java8的新特性,可以在Spring的回调接口中使用 lambda 表达式

环境

  • JDK版本 1.8.0_74
  • Spring版本 4.2.6.RELEASE
  • 依赖管理 Maven

简单示例

1. 加入依赖

<dependencies>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>4.2.6.RELEASE</version>    </dependency></dependencies>

2. 类路径下创建Beans.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 id="..." class="...">        <!-- collaborators and configuration for this bean go here -->    <!--    </bean>    -->    <bean id="student" class="com.erick.hello.Student">        <property name="name" value="tom" />        <property name="age" value="12" />    </bean>    <!-- more bean definitions go here --></beans>

3. 创建Student.java

package com.erick.hello;public class Student {    private int age;    private String name;    //getter and setter    //...}

4. 使用

ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");Student stu = (Student)ctx.getBean("student");System.out.println(stu.getName());
0 0
原创粉丝点击