栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring程序开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring程序开发

Spring
  • 一、Spring核心API——ApplicationContext
    • 1.ApplicationContext接口类型
    • 2.重量级资源
  • 二、程序开发
  • 三、细节分析
    • 1.名词解释
    • 2.Spring工厂的相关的方法
    • 3.配置文件中需要注意的细节

一、Spring核心API——ApplicationContext

作用:Spring提供的ApplicationContext这个工厂,用于对象的创建
好处:解耦合

1.ApplicationContext接口类型

接口:屏蔽实现的差异
非web环境:ClassPathXmlApplicationContext(main junit)
web环境下:XmlWebApplicationContext

2.重量级资源

(1)ApplicationContext工厂的对象占用大量的内存,
所以不会频繁的创建对象:一个应用只会创建一个工厂对象。
(2)ApplicationContext工厂:一定是线程安全的(可以多线程并发访问)

二、程序开发

1.创建类型
创建一个类
public class Person {
}
2.配置文件的配置 applicationContext.xml
bean id=“person” class=“www.study.basic.Person”/
3.通过工厂类,获得对象 ApplicationContext
——ClassPathXmlApplicationContext
ApplicationContext ctx=new ClassPathXmlApplicationContext(“/applicationContext.xml”);
Person person=(Person) ctx.getBean(“person”);

三、细节分析 1.名词解释

Spring工厂创建的对象,叫做bean或者组件(componet)

2.Spring工厂的相关的方法
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");

        //通过这种方式获得对象就不需要强制类型转换了
        Person person=ac.getBean("person",Person.class);
        System.out.println("person="+person);

        //要求在当前Spring的配置文件中,只有一个bean标签的类型是Person的
        Person person=ac.getBean(Person.class);
        System.out.println("person="+person);

        //获取的是Spring工厂配置文件中所有bean标签的id值
        String [] bdn=ac.getBeanDefinitionNames();
        for (String i:bdn){
            System.out.println("beanDefinitionName="+i);
        }

        //根据类型来获得Spring配置文件中对应的id值
        String [] beanNamesForType=ac.getBeanNamesForType(Person.class);
        for (String id:beanNamesForType){
            System.out.println("id="+id);
        }

        //用于判断是否存在指定id值的bean,不能判断name属性
        if (ac.containsBeanDefinition("person")){
            System.out.println("true="+true);
        }else{
            System.out.println("false="+false);
        }

        //用于判断是否存在指定的id值的bean,也可以判断name属性
        if (ac.containsBean("person")){
            System.out.println("true="+true);
        }else{
            System.out.println("false="+false);
        }
3.配置文件中需要注意的细节

1.只配置class属性也可以完成对象的创建
使用Person person=ac.getBean(Person.class);,而且会有默认id生成
(1)应用场景:如果这个bean只使用一次,那么就可以省略id值。如果这个bean会使用多次,或者被其他bean引用就需要设置id值
2.name属性
(1)作用:用于在Spring的配置文件中,为bean对象定义别名
(2)相同:都可以完成对象的创建
(3)区别:别名可以定义多个,但是id属性只能有一个值。
XML的id属性值,命名要求:必须以字母开头,后边可以跟字母、数字、下划线、连字符,不能以特殊字符开头;name属性的值,命名时没有要求。如今XML id 属性的限制没了。
代码区别: containsBeanDefinition:用于判断是否存在指定id值的bean,不能判断name属性;containsBean:用于判断是否存在指定的id值的bean,也可以判断name属性。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1028225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号