1.环境搭建
-
Spring的jar包
#设置pom 依赖 <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.4.RELEASE</version> </dependency>
-
Spring的配置文件
1. 配置文件的放置位置:任意位置 没有硬性要求 2. 配置文件的命名 :没有硬性要求 建议:applicationContext.xml 思考:日后应用Spring框架时,需要进行配置文件路径的设置。
2.Spring的核心API
-
ApplicationContext
作用:Spring提供的ApplicationContext这个工厂,用于对象的创建 好处:解耦合
-
ApplicationContext接口类型
接口:屏蔽实现的差异 非web环境 : ClassPathXmlApplicationContext (main junit) web环境 : XmlWebApplicationContext
- 重量级资源
ApplicationContext工厂的对象占用大量内存。(实现类占用内存大) 不会频繁的创建对象 : 一个应用只会创建一个工厂对象。 ApplicationContext工厂:一定是线程安全的(多线程并发访问)
3. 程序开发
1. 创建类型
2. 配置文件的配置 applicationContext.xml
<bean id="person" class="com.baizhiedu.basic.Person"/>
3. 通过工厂类,获得对象
ApplicationContext
|- ClassPathXmlApplicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
Person person = (Person)ctx.getBean("person");
4. 细节分析
-
名词解释
Spring工厂创建的对象,叫做bean或者组件(componet)
-
Spring工厂的相关的方法
//通过这种方式获得对象,就不需要强制类型转换 Person person = ctx.getBean("person", Person.class); System.out.println("person = " + person); //当前Spring的配置文件中 只能有一个<bean class是Person类型 Person person = ctx.getBean(Person.class); System.out.println("person = " + person); //获取的是 Spring工厂配置文件中所有bean标签的id值 person person1 String[] beanDefinitionNames = ctx.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println("beanDefinitionName = " + beanDefinitionName); } //根据类型获得Spring配置文件中对应的id值 String[] beanNamesForType = ctx.getBeanNamesForType(Person.class); for (String id : beanNamesForType) { System.out.println("id = " + id); } //用于判断是否存在指定id值的bean if (ctx.containsBeanDefinition("a")) { System.out.println("true = " + true); }else{ System.out.println("false = " + false); } //用于判断是否存在指定id值的bean if (ctx.containsBean("person")) { System.out.println("true = " + true); }else{ System.out.println("false = " + false); }
-
配置文件中需要注意的细节
1. 只配置class属性 <bean class="com.baizhiedu.basic.Person"/> a) 上述这种配置 有没有id值 com.baizhiedu.basic.Person#0 b) 应用场景: 如果这个bean只需要使用一次,那么就可以省略id值 如果这个bean会使用多次,或者被其他bean引用则需要设置id值 2. name属性 作用:用于在Spring的配置文件中,为bean对象定义别名(小名) 相同: 1. ctx.getBean("id|name")-->object 2. <bean id="" class="" 等效 <bean name="" class="" 区别: 1. 别名可以定义多个,但是id属性只能有一个值 2. XML的id属性的值,命名要求:必须以字母开头,字母 数字 下划线 连字符 不能以特殊字符开头 /person name属性的值,命名没有要求 例如: /person name属性会应用在特殊命名的场景下:/person (spring+struts1) XML发展到了今天:ID属性的限制,不存在 /person 3. 代码 //用于判断是否存在指定id值得bean,不能判断name值 if (ctx.containsBeanDefinition("person")) { System.out.println("true = " + true); }else{ System.out.println("false = " + false); } //用于判断是否存在指定id值得bean,也可以判断name值 if (ctx.containsBean("p")) { System.out.println("true = " + true); }else{ System.out.println("false = " + false); }
5. Spring工厂的底层实现原理
Spring工厂是可以调用对象私有的构造方法创建对象
6. 思考
问题:未来在开发过程中,是不是所有的对象,都会交给Spring工厂来创建呢?
回答:理论上 是的,但是有特例 :实体对象(entity)是不会交给Spring创建,它是由持久层框架进行创建。