简单的使用spring

1.导包

2.编写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="stu" class="com.zyj.springtest.bean.Student">
        <property name="name" value="zs"></property>
    </bean>
</beans>

3.在代码中Spring应用的上下文

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

4.生成对象

Student stu = context.getBean("stu",Student.class);
stu.study();

这个stu对象就是和正常new出来的一样


使用Spring依赖注入

示例:

<bean id="bdi" class="com.zyj.springtest.daoimp.BookDaoImp">
</bean>
<bean id="ibbi" class="com.zyj.springtest.bizimp.IBookBizImp">
    <property name="dao" ref="bdi"></property>
</bean>
<bean id="bc" class="com.zyj.springtest.controller.BookController">
    <property name="ib" ref="ibbi"></property>
</bean>

IBookBizImp类中有个成员变量,变量名为dao

BookController类中有个成员变量,变量名为ib

这里可以在xml文件中为这两个成员变量赋值
但是这两个成员变量需要有set/get方法

2.<bean>标签中属性scope="xxxx"

  • prototype:原型模式,每次通过getBean获取该bean就会新产生一个实例,创建后spring将不再对其管理
  • singleton:单例模式,当spring创建applicationContext容器的时候,spring会欲初始化所有的该作用域实例,加上lazy-init就可以避免预处理
  • request:每次请求都新产生一个实例,和prototype不同就是创建后,接下来的管理,spring依然在监听
  • session:每次会话,同上
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,891评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,947评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,760评论 18 399
  • 来源:关于Spring IOC (DI-依赖注入)你需要知道的一切作者:zejian Dao层(AccountDa...
    杨井阅读 5,362评论 0 27
  • 许你一世繁华 岩定花可攀 不知何人何面 见遇犹匆匆 不知何年何月 散我相重逢
    sunshine1o阅读 146评论 1 1