1、如何理解 Spring 框架

简单来说,Spring 是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架

因为以前写代码的时候,在使用类对象的时候,经常需要实例化创建(new 出来)很多对象,有时候只需要实例化一次对象即可(不管这个对象是 service 或者 dao),让这个对象去做该做的事情。

而Spring框架就是管理这些对象的,让 Spring 容器装配管理这些对象,程序猿需要时再取出来使用,让对象的创建和使用更加方便。

【Bean其实就是一个new好的对象】

2、使用 Spring 的好处

  • 方便解耦,简化开发

    Spring就是一个大工厂,专门负责生成Bean,可以将所有对象创建和依赖关系维护由Spring管理。

  • AOP编程的支持

    Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能。

  • 声明式事务的支持

    只需要通过配置就可以完成对事务的管理,而无需手动编程。

  • 方便程序的测试

    Spring对Junit4支持,可以通过注解方便的测试Spring程序。

  • 方便集成各种优秀框架

    Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的支持。

  • 降低JavaEE API的使用难度

    对JavaEE开发中一些难用的API(JDBC、JavaMail、远程调webservice用等),都提供了封装,使这些API应用难度大大降低。

3、说了这么多,是骡子是马,拉出来溜溜(案例演示)

  • 创建接口和实现类

    public interface UserService {
    void add();
    } =============================================================================
    public class UserServiceImpl implements UserService {
    @Override
    public void add() {
    System.out.println("创建用户....");
    }
    }
  • 不使用 Spring 调用对象方法

    public class ServiceTest {
    public static void main(String[] args) {
    UserService userService=new UserServiceImpl();
    userService.add();
    }
    }

    控制台打印结果日志:创建用户....

  • 使用 Spring 管理对象

    首先需要创建 bean.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 【对象】-->
    <bean id="userService" class="com.example.demo.service.impl.UserServiceImpl"/>
    </beans>
     public class ServiceTest {
    public static void main(String[] args) { //1.加载beans.xml 这个spring的配置文件,内部就会创建对象
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //2.从spring容器获取 userSerivce对象
    UserService userSerivce1 = (UserService) context.getBean("userService");
    userSerivce1.add(); UserService userSerivce2 = (UserService) context.getBean("userService");
    userSerivce2.add(); System.out.println(userSerivce1);
    System.out.println(userSerivce2);
    }
    }

控制台打印结果日志如下:

创建用户....

创建用户....

com.example.demo.service.impl.UserServiceImpl@3b088d51

com.example.demo.service.impl.UserServiceImpl@3b088d51

可以看出是Spring在启动加载配置文件 bean.xml 的时候,会在容器中创建好这个对象,需要使用的时候直接获取就可以。

相比以前每次都要 new(频繁 new 对象的过程对程序开销很大) 一个对象。交给 Spring 容器后这个对象只会创建一次,所以打印的地址值是一样的。

2、对 Spring 中 IOC 和 DI 讲解

  • IoC 反转控制

    就是将原本在程序中手动创建 UserService 对象的控制权,交由 Spring 框架管理。简单说就是创建 UserService 对象控制权被反转到了 Spring 框架。

  • DI 依赖注入

    在 Spring 框架负责创建 Bean 对象时,动态的将依赖对象注入到 Bean 组件。

  • 对依赖注入(DI)案例演示

    public class UserServiceImpl implements UserService {
    
        private String name;
    
     	// 可以注释掉 getName 方法
    public String getName() {return name;} // setName 方法不可以注释掉
    public void setName(String name) {this.name = name;} @Override
    public void add() {
    System.out.println("创建用户...." + name);
    }
    }
     <?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 【对象】-->
    <bean id="userService" class="com.example.demo.service.impl.UserServiceImpl">
    <!-- 依赖注入数据,调用属性的set方法 -->
    <property name="name" value="zhangsan"></property>
    </bean>
    </beans>

    运行原来的 Main 方法,控制台打印结果日志如下:

    创建用户....zhangsan

    创建用户....zhangsan

    com.example.demo.service.impl.UserServiceImpl@7a187f14

    com.example.demo.service.impl.UserServiceImpl@7a187f14

  • 重点

    UserServiceImpl 中如果注释掉 getName ,程序不出错。如果注释掉 setName 方法,则会报错如下所示,至于报错的原因,请看下一篇讲解。

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.example.demo.service.impl.UserServiceImpl]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1718)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1433)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
    at com.example.demo.testservice.ServiceTest.main(ServiceTest.java:16)
    Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.example.demo.service.impl.UserServiceImpl]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)
    at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1714)
    ... 13 more

Spring 讲解(一 )的更多相关文章

  1. spring讲解

    今日先简单介绍一下Spring bean 的 5 种效果域,然后详细介绍 singleton 和 prototype 这两种最常用的效果域. JavaSpring Bean的五种效果域 效果域的种类 ...

  2. Spring讲解-----------表达式语言

    转自:https://blog.csdn.net/u011225629/article/details/47143083 5.1  概述5.1.1  概述       Spring表达式语言全称为“S ...

  3. Spring 讲解(六)

    如何理解 Spring 中的 AOP 一.AOP 的概述 AOP(Aspect Oriented Programming):面向切面编程,通过预编译方式和运行期动态代理来实现程序功能的统一维护的一种技 ...

  4. Spring 讲解(五)

    Spring 中使用 xml 配置开发和使用注解开发案例 1.Spring 中使用 xml 配置开发案例 接口 public interface UserDao { void add(User use ...

  5. Spring 讲解(四)

    Spring 中使用注解注入 注解:就是一个类,使用 @ 注解名称. 实际开发中:使用注解取代 xml 配置文件. 1.常用注解释义 @component 取代 <bean class=&quo ...

  6. Spring 讲解(二 )

    1.Spring 容器加载的3种方式 public class ServiceTest { public static void main(String[] args) { //Spring容器加载有 ...

  7. Spring讲解(三)

    依赖注入Bean属性,使用xml配置 1.构造方法注入 案例代码演示 public class User { private String username; private String passw ...

  8. ARTS第一周

    开始进行的第一周. 1.Algorithm:每周至少做一个 leetcode 的算法题2.Review:阅读并点评至少一篇英文技术文章3.Tip:学习至少一个技术技巧4.Share:分享一篇有观点和思 ...

  9. 【Spring】SpringMVC入门示例讲解

    目录结构: // contents structure [-] SpringMVC是什么 Spring MVC的设计原理 SpringMVC入门示例 1,复制Jar包 2,Web.xml文件 3,My ...

随机推荐

  1. python request(HttpRequest对象)请求的属性、方法笔记

    1.属性 path:表示提交请求页面完整地址的字符串,不包括域名,如"/music/bands/the_beatles/". method:表示提交请求使用的HTTP方法.(GET ...

  2. Lock之ReentrantLock及实现生产者消费者和死锁

    Lock是顶层接口,它的实现逻辑并未用到synchronized,而是利用了volatile的可见性.ReentrantLock对了Lock接口的实现主要依赖了Sync,而Sync继承了 Abstra ...

  3. Java Web学习总结(9)学习总结-JSTL

    一,JSTL概述 JSTL(JSP Standard Tag Library),JSP标准标签库,可以嵌入在jsp页面中使用标签的形式完成业务逻辑等功能.jstl出现的目的同el一样也是要代替jsp页 ...

  4. JSON对象及方法

    1.JSON JSON 包括 JSON 字符串和 JSON 对象.JSON 通常用于与服务端交换数据,在给服务器接收和发送数据时用的都是字符串,可以是 JSON 字符串或者一般的键值对字符串.把Jav ...

  5. linux0.11内核源码——用户级线程及内核级线程

    参考资料:哈工大操作系统mooc 用户级线程 1.每个进程执行时会有一套自己的内存映射表,即我们所谓的资源,当执行多进程时切换要切换这套内存映射表,即所谓的资源切换 2.但是如果在这个进程中创建线程, ...

  6. webBrowser强制在本窗口打开,禁止在新窗口打开

    有时需要用WebBrowser加载URL,来实现某些功能.而这时,我们就不希望所打开的页面中的链接,在新窗口中打开,因为这样的话,实际上是用系统默认的浏览器打开了,从而脱离了你的WebBrowser, ...

  7. BZOJ 2281: [Sdoi2011]黑白棋(dp+博弈论)

    传送门 解题思路 首先发现可以把相邻的黑白棋子之间的距离看成一堆棋子,那么这个就可以抽象成\(Nim\)游戏每次可以取\(d\)堆这个游戏,而这个游戏的\(SG\)值为\(x\%(d+1)\),那么题 ...

  8. BZOJ 4399: 魔法少女LJJ(线段树)

    传送门 解题思路 出题人真会玩..操作\(2\)线段树合并,然后每棵线段树维护元素个数和.对于\(6\)这个询问,因为乘积太大,所以要用对数.时间复杂度\(O(nlogn)\) 代码 #include ...

  9. CodeForces - 849B 几何

    题意:给n个点,问是否能两条平行线覆盖所有的点 思路:因为要求全部覆盖,所以我们第一个点肯定是会入其中一条直线,其实只用判前三个点的所有情况即可 #include<stdio.h> #in ...

  10. window server 2008 r2 安装ftp

    一.安装ftp服务 1.在服务管理器“角色”右键单击“添加角色”.  2.下一步. 3.勾选“Web 服务器(IIS)”,下一步. 4.勾选“FTP 服务器”,下一步. 5.安装完成,点击“关闭”.  ...