参考 编程界翁老师 之课程及资料:编程界翁老师/day01Spring

(代码对应的视频在 哔哩哔哩 ( ゜- ゜)つロ 乾杯~ Bilibili

1)手写迷你"框架",模拟 Spring解决"new实例带来的三个问题"

不通过框架,手动new对象有3个缺点:

  1. 创建出来的对象,其类型不方便修改(不能控制类型)
  2. test1()方法的运行结果,可见AccountService手动new出来,随后执行CURD方法:
  3. 有些类对象,我们希望在项目启动的时候 实例化,而不是在 要使用的时候 才实例化(不能控制时机)

为了解决以上3个缺点,可以模仿spring原理,写一个demo(仅列出关键代码):

测试方法:

public class TestFactory {/*测试方法 test01()模拟 账户的创建*/@Testpublic void test01() {//1:定义一个业务类:账户ServiceAccountService as = new AccountServiceImpl();//2:创建一个账户数据Account account = new Account(1001L, "jack", 1000.000);//3:账户数据 添加,更新,查找as.saveAccount(account);as.updateAccount(account);Account acc = as.findAccount(1001L);System.out.println(acc);}/*测试方法 test01()模拟 单例模式 创建 AccountService 对象*/@Testpublic void test2() {System.out.println("test2");//1:定义 两个业务类(账户Service)的 对象AccountService as1 = (AccountService) MyBeanFactory.getBean("service", "singleton");AccountService as2 = (AccountService) MyBeanFactory.getBean("service", "singleton");System.out.println(as1);System.out.println(as2);//2:创建一个账户数据Account account = new Account(1001L, "jack", 1000.000);//3:账户数据 添加,更新,查找as1.saveAccount(account);as1.updateAccount(account);Account acc = as1.findAccount(1001L);System.out.println(acc);}}

通过 工厂模式+读取配置文件+反射,模拟Spring创建类对象(可认为 MyBeanFactory类 是一个“迷你Spring框架”):

// 1:工厂类
public class MyBeanFactory {// 2:容器(container)创建(模仿创建了一个Spring容器)private static Map<String, Object> container = new HashMap<String, Object>();private static Properties properties;// 3:// 静态代码块中 通过读取配置文件// 加载 类信息 到 properties对象中static {// 加载类型信息properties = new Properties();// 解析InputStream is = MyBeanFactory.class.getResourceAsStream("/mybean.properties");try {properties.load(is);//可以这里初始化对象,放到容器中,也可以在使用时再初始化} catch (IOException e) {}}//4:查找对象(类似单例模式、工厂模式)public static Object getBean(String id, String singleton) {if ("singleton".equals(singleton)) {//查找 container中是否已有 所需类(如AccountServiceImpl类)的对象Object obj = container.get(id);//容器里面没有 所需 类的对象if (obj == null) {String str = properties.getProperty(id);Class clz = null;try {clz = Class.forName(str);Object o = clz.newInstance();// 把 新对象 添加到容器中container.put(id, o);return o;} catch (Exception e) {e.printStackTrace();}} else {//重用(复用)同一个对象return obj;}} else {// 多实例 prototype// 容器(container)里面没有 所需 类(如AccountServiceImpl类)的对象String str = properties.getProperty(id);Class clz = null;try {clz = Class.forName(str);Object o = clz.newInstance();return o;} catch (Exception e) {e.printStackTrace();}}return null;}
}

配置文件(mybean.properties)的内容:

service=service.impl.AccountServiceImpl
dao=dao.impl.AccountDaoImpl

test1()方法的运行结果,可见AccountService被手动new出来,随后执行CURD方法:

test2()方法的运行结果,可见AccountService对象 被MyBeanFactory类(的静态方法getBean)所创建,且为单例模式,随后执行CURD方法:

2) 同上套路,写一个Spring入门程序

pom文件中,导入spring:

       <!-- spring基础--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.8.RELEASE</version></dependency>

配置文件(beans.xml)的内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="Index of /schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"><bean class="dao.impl.AccountDaoImpl" id="dao"></bean><bean class="service.impl.AccountServiceImpl" id="service" scope="prototype"></bean></beans>

测试方法:

public class TestFactory {@Testpublic void test01() {// 1:使用maven依赖了spring基本包// 2:初始化spring ioc容器// BeanFactory满足基本功能的容器:顶层接口// ApplicationContext高级功能的容器:子抽象类// ClassPathXmlApplicationContext实现类BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");// 3:获取service对应的对象AccountService as1 = (AccountService) beanFactory.getBean("service");AccountService as2 = (AccountService) beanFactory.getBean("service");System.out.println(as1);System.out.println(as2);as1.saveAccount(null);}
}

留意ClassPathXmlApplicationContext类(以上代码通过此类的对象,加载配置文件、创建类对象),它继承了抽象类AbstractApplicationContext,实现了BeanFactory接口:

ClassPathXmlApplicationContext类的父子关系

test01()方法的运行结果如下, 可见AccountService对象被ClassPathXmlApplicationContext对象beanFactory 所创建,且为单例模式(由于在beans.xml中配置了 scope="prototype"):

运行结果
单例配置

3) 依赖注入(DI)

实体类:

package bean;import java.util.*;public class Account {// 基本数据类型private Long id;private String account;private Double money;// 集合private String[] array;private List<String> list;private Set<String> set;private Map<String, Integer> map;private Properties properties;// 对象private Date birthday;public String[] getArray() {return array;}public void setArray(String[] array) {this.array = array;}public List<String> getList() {return list;}public void setList(List<String> list) {this.list = list;}public Set<String> getSet() {return set;}public void setSet(Set<String> set) {this.set = set;}public Map<String, Integer> getMap() {return map;}public void setMap(Map<String, Integer> map) {this.map = map;}public Properties getProperties() {return properties;}public void setProperties(Properties properties) {this.properties = properties;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public Account() {}public Account(Long id, String account, Double money) {this.id = id;this.account = account;this.money = money;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", account='" + account + ''' +", money=" + money +'}';}
}

beans.xml文件中,添加:

    <!--    通过构造函数注入--><bean class="bean.Account" id="account1"><constructor-arg name="id" value="1001"></constructor-arg><constructor-arg name="account" value="jacky"></constructor-arg><constructor-arg name="money" value="18000"></constructor-arg></bean><!--    通过setter方法注入--><bean class="bean.Account" id="account2"><property name="id" value="1002"></property><property name="account" value="Monica"></property><property name="money" value="9999"></property></bean>

测试方法:

@Testpublic void test02_DI() {System.out.println("test02_DI");BeanFactory beanFactory = new ClassPathXmlApplicationContext("beans.xml");Account ac1 = (Account) beanFactory.getBean("account1");Account ac2 = (Account) beanFactory.getBean("account2");System.out.println(ac1);System.out.println(ac2);}

运行结果:

test02_DI
Account{id=1001, account='jacky', money=18000.0}
Account{id=1002, account='Monica', money=9999.0}

spring读取properties配置文件_spring简介相关推荐

  1. spring读取properties配置文件_Spring-1

    spring共四天 第一天:spring框架的概述以及spring中基于XML的IOC配置 第二天:spring中基于注解的IOC和ioc的案例 第三天:spring中的aop和基于XML以及注解的A ...

  2. 如何在spring中读取properties配置文件里面的信息

    如何在spring中读取properties配置文件里面的信息 <!-- 正文开始 --> 一般来说.我们会将一些配置的信息放在.properties文件中. 然后使用${}将配置文件中的 ...

  3. Spring Boot——读取.properties配置文件解决方案

    解决方案 Spring Boot 读取properties配置文件时,默认读取的是application.properties. 方法一:@ConfigurationProperties注解方式 @C ...

  4. Spring @Value:读取Properties配置文件

    非 @Value方式:基于ResourceLoader读取Properties配置文件 以下为通过Spring @Value:读取Properties配置文件 1.1 前提 测试属性文件:advanc ...

  5. Java 读取 .properties 配置文件的几种方式

    Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配 ...

  6. Spring读取xml配置文件的原理与实现

    2019独角兽企业重金招聘Python工程师标准>>> Spring读取xml配置文件的原理与实现 本篇博文的目录: 一:前言 二:spring的配置文件 三:依赖的第三方库.使用技 ...

  7. java如何读取.properties配置文件

    Properties类 1.简介 Properties 继承于 Hashtable.表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串.由于继承于Hashtable,当从配置文件中读取出配 ...

  8. Java中读取properties配置文件的八种方式总结

    一.前言 在做Java项目开发过程中,涉及到一些数据库服务连接配置.缓存服务器连接配置等,通常情况下我们会将这些不太变动的配置信息存储在以 .properties 结尾的配置文件中.当对应的服务器地址 ...

  9. Java读取Properties配置文件

    目录 1.Properties类与Properties配置文件 2.Properties中的主要方法 3.示例 1.Properties类与Properties配置文件 Properties类继承自H ...

  10. 【转载】java读取.properties配置文件的几种方法

    读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的): 一.通过jdk提供的java.util.Properties类. 此类继承自java.uti ...

最新文章

  1. 【Groovy】字符串 ( 字符串注入函数 | asBoolean | execute | minus )
  2. 解决.gitgnore加入.idea无效问题
  3. android recyclerview gradle,Android RecyclerView 的简单使用
  4. java 运行环境注册表_Java运行环境与Windows注册表
  5. 解决 idea 中 jsp 修改后页面不生效
  6. 在服务器上远程使用tensorboard查看训练loss和准确率
  7. 大三软件工程小项目-小技术集合总结
  8. java 后台自动刷新请求_spring oauth2+JWT后端自动刷新access_token
  9. 1036 和奥巴马一起学编程
  10. 回溯法 之 马周游(马跳日)问题
  11. AspNetPager 存储过程
  12. 字节跳动8年经验,亲身经历教你如何从小白晋升月薪过万的测试工程师
  13. css的div纵向居中
  14. 程序人生 | 文艺程序员使用代码发展诗歌
  15. 【python】99 Bottles Of Beer
  16. java多数据库开发evn,Java,在多线程evnironments中通过散列统一划分传入的工作
  17. python爬取京东图书_Python抓取京东图书评论数据
  18. 时间观——《天行九歌》第51集《一叶知秋》台词与典故
  19. 排序算法之归并排序 ( C语言版 )
  20. js-多个果冻按钮之当前果冻按钮弹性特效

热门文章

  1. Spring配置属性文件
  2. 关于SVN出现 svn working copy locked的原因及解决方法
  3. win8游戏开发教程开篇
  4. ASP.NET MVC 3和Razor中的@helper 语法
  5. 时间选择插件jquery.timepickr
  6. LINUX下设置定时运行PERL脚本
  7. 智能优化算法:蛇优化算法-附代码
  8. 【LeetCode】【数组】题号:73,矩阵置零
  9. 【Tensorflow/keras】KeyError: ‘loss‘
  10. 编写代码模拟三次密码输入的场景。