Spring框架基础

简介

  • Spring是一个基于IOC和AOP的结构J2EE系统的框架
  • 核心思想:IoC、AOP
  • 简化企业开发,帮助分离对象之间的依赖关系
  • spring能解决的问题
    • 解耦应用程序,简化开发流程
    • AOP支持
    • 声明式事务
    • 集成junit4
    • 方便集成各种开源的优秀框架
    • 降低JavaEE API的使用难度

程序的耦合

  • 耦合:程序间的依赖关系
    • 包括:类之间的依赖、方法间的依赖
  • 解耦:降低程序键的依赖关系
    • 实际开发中:应该做到编译期不依赖,运行时才依赖
    • 解耦的思路:
      • 1.使用反射来创建对象,而避免使用new关键字
      • 2.通过读取配置文件来获取想要创建的对象全限定类名
  • 例:注册数据库驱动时 
    DriverManager.registerDriver(new com.mysql.jdbc.Driver())//通过new创建
    Class.forName("com.mysql.jdbc.Driver")//通过反射创建

     

Spring IOC

IOC 控制反转 是Spring的基础,Inversion Of Control 简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象和保存对象

通过xml配置创建类对象步骤:

1.创建maven工程,在pom.xml文件配置spring的jar包坐标

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

2.在src/main/resources下创建spring的xml配置文件,配置bean对象

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 由spring创建管理对象 -->
    <bean id="accountService" class="com.test.service.AccountService">
        <!--给构造函数参数赋值-->
        <constructor-arg name="username" value="zhansan"/>
        <!--给类的成员变量age赋值,该类必须要有setAge()方法-->
        <property name="age" value="10"/>
    </bean>
</beans>

3.获取spring容器根据id获取bean对象

public static void main(String[] args) {

        //获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
        //根据id获取bean对象
        AccountService accountService = ac.getBean("accountService", AccountService.class);
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值