ssm-spring入门

ssm-spring入门

Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。以 IoC(Inverse of Control,控制反转)和 AOP(Aspect Oriented Programming,面向切面编程)为内核。是Spring全家桶(Spring framework、SpringMVC、SpringBoot、Spring Cloud、Spring Data、Spring Security 等)的基础和核心。

初识Spring

从简单工程入手:
  1. 创建实体类:

  2. resources目录下创建spring配置xml文件:
  3. <?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.zx.demo.spring.beans.Student"/>
    </beans>
    每个bean代表一个实体,id是别名,class是类全称。
  4. 测试:
  5. @Test
    public void student() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    }
    ClassPathXmlApplicationContext: 读取装配spring xml配置文件。
    运行结果如下:

    可以看出在装配完spring xml配置文件后,实体类构造方法就已经创建。

依赖注入:

IOC(控制反转)是spring框架的核心思想之一,而这一思想的重要实现方式是DI(依赖注入),依赖注入原理是使用反射,在上诉的例子上用依赖注入来获取实例:
  1. 修改spring配置文件:beans.xml
  2. <bean id="student" class="com.zx.demo.spring.beans.Student">
        <property name="id" value="123"/>
        <property name="name" value="张三"/>
    </bean>
    这个配置文件中,声明了一个实体对象 student,并对其属性 id,name进行了赋值。
  3. 通过配置文件获取该实例
  4. @Test
    public void student() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student);
    }
    获取实例的核心方法是: context.getBean("student"),其原理是BeanFactory通过反射获取。
  5. 查看结果

使用注解

上面介绍了使用配置文件注入对象的方式,接下来看看如何使用注解来注释对象:
  1. 修改spring配置文件:beans.xml

  2. 要使用注解,首先要添加注解的支持: <context:annotation-config/>
    其次添加扫描包名: <context:component-scan base-package="com.zx.demo.spring.beans"/>
  3. 在实体上添加注解:

  4. 这里用到了两个注解: @Component @Value,其中Component对应<bean>标签,Value对应<property>标签
    整个注解等同于:
    <bean id="student" class="com.zx.demo.spring.beans.Student">
        <property name="id" value="123"/>
        <property name="name" value="张三"/>
    </bean>
  5. 查看结果

  6. 和使用配置文件注入得到相同效果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值