spring 框架 简单实例

1.导入jar包(此处用的是4.1.6版本)

spring各个版本的下载地址如下:
[http://repo.springsource.org/libs-release-local/org/springframework/spring/ ]

    commons-logging-1.1.3.jar
    spring-beans-4.1.6.RELEASE.jar
    spring-context-4.1.6.RELEASE-javadoc.jar
    spring-context-4.1.6.RELEASE.jar
    spring-core-4.1.6.RELEASE.jar
    spring-expression-4.1.6.RELEASE.jar

2.编写配置文件 applicationContext.xml 放入src目录下

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- student为你想要实例化的名字  com.ly.entity.Student为实体类对应的路径    prototype 为多例模式(可以不写,默认为单例模式  singleton) -->
     <bean id="student" class="com.ly.entity.Student" scope="prototype">
    </bean> 
</beans>

3.编写实体类 Student

package com.ly.entity;

public class Student {
    private Integer id;
    private String name;
    private User user;
    public Student() {
        super();
    }

    public Student(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name  + "]";
    }


}

4.编写测试类 StudentService

package com.ly.service;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ly.entity.Student;

public class StudentService {
    public static Student getStudent(){
    //读取配置文件
    ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取配置文件中 bean标签 id 为student的类
        Student stu = (Student)a.getBean("student");
        //通过set方法 对stu进行赋值
        stu.setId(123);
        stu.setName("aa");
        return stu;
    }

    public static void main(String[] args) {
        Student stu = getStudent();
        System.out.println(stu);
    }

}

运行则可看到结果,一个简单的spring 框架搭建的工程完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值