Spring框架的基本使用与标签

Spring框架的基本使用与标签

框架的概念

(一)从现实生活的角度来看: 框架,就好像是 “风筝”骨架。 如果我给你一个“风筝”的骨架,你只需要去往这个“风筝骨架”上,贴上一层纸。一个现成的风筝就做好啦~~ 如果没有“风筝的骨架”,那你需要,自己去找“竹子”“木材”“铁丝”等等东西,然后还要“自己手工”的做出一个“风筝骨架”来。。。呵呵,想一想,如果你做100个风筝的话。。。估计就要把人给“累死”啦。。。
(二)从技术角度来看
框架就是半个做好的程序。如果我们要编写程序的话,只需要花费 一半的时间精力,就可以完成,整个程序了。。。 因为这个现成的“框架”,已经帮我们做好了了一半啦。。。 这就是为什么,要使用“框架”,因为这样能够让我们,更加快速的开发出程序来。。。 当然了,其实也可以不用框架,那样的话。。。就要上面那个“风筝”似的。。。太累了。。

总结:spring框架可以简化我们的开发,使开发更高效,快捷

控制翻转概念(IoC)

没用spring之前,如果想用自己创建的一个学生类

Student student = new Student

spring相当于一个容器,在spring的配置文件中管理这这些类,以前的方法是我们自己想用就new出来一个,是我们在控制这这些类做什么事,后者是spring在帮我们管理这些类,如:给学生类的成员变量赋值。

spring入门案例

实体类Student

package com.itheima.domain;

public class Student {
   
    public Student() {
   

    }
    public void save(){
   
         System.out.println("student..running");
    }
}

1.导包(maven的pom文件中导入spring的jar包)

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

2.在配置文件的目录resources下创建spring的核心配置文件(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.xsd">
<bean id="student" class="com.itheima.domain.Student"/>
</beans>

使用spring管理类,配置文件中定义bean标签,id属性是唯一标识,见名知义,class属性是student类的全限定类名。

3.在主方法中使用spring创建student对象

package com.itheima.controller;

import com.itheima.domain.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
   
    public static void main(String[] args) {
   
        //读取spring的核心配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //使用spring中getBean,参数传递id属性值,就可以获取student对象
        Student student = (Student) ctx.getBean("student");
        student.save();
    }
}

控制台打印效果

student…running

bean标签中scope属性

<!--singleton是scope的默认属性,表示单例对象,在创建对象时只会创建一个对象-->
<bean id="student" scope="singleton" class="com.itheima.domain.Student"/>
<!--prototype表示多例对象,在创建对象时每调一次getBean方法都会创建一个不同的对象-->
<bean id="student" scope="prototype" class="com.itheima.domain.Student"/>

静态工厂与实例工厂创建bean

工厂类

package com.itheima.factory;

import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

public class UserServiceFactory {
   
    public static UserService getUserService(){
   
        return new 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值