Spring核心配置文件的理解以及Bean作用域

21 篇文章 0 订阅

最近一直在学习Spring存了一些笔记,现在打算梳理一下。笔记尽可能去记得比较的详细,不然回头看了看不懂等于白费.
首先我使用的是IDEA创建maven工程然后再pom.xml中导入依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>

对Spring核心配置文件(application-config.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">
    <!--
    声明Java对象交给Spring创建和管理
    class:类的全限定名,不能是接口(Spring使用反射机制创建对象)
    id:自定义的对象名称,要求是唯一值。表示在Spring中的对象名称
    通过这个名称可以从Spring中找到对象,获取对象

    <bean id="someService" class="com.bjpowernode.service.SomeSerivceImpl"/>
    <bean>等同于
    SomeService someService=new com.bjpowernode.service.SomeServiceImpl();
    对象是放到Spring容器中(Map<id,对象>)
    -->
    <bean id="someService" class="com.bjpowernode.service.SomeServiceImpl"/>
</beans>

从配置文件中可以看出Spring本质就是对JavaBean使用xml文件来进行管理,那么现在可以通过读取配置文件来访问对应的JavaBean了

public static void main(String[] agrs){
    String config="appcation-config.xml";
    /*创建Spring的容器对象,根据Spring配置文件的位置,使用接口的不同实现类
     *如果Spring的配置文件是类路径(classpath),使用ClassPathXmlApplicationContext
    * */
    ApplicationContext context=new ClassPathXmlApplicationContext(config);
    /*从容器中获取对象,使用getBean("<bean>的id")
    * */
    SomeService someService=(SomeService) context.getBean("someService");
    //调用SomeService的函数
    someService.doSome();
}

在Spring中的Bean是有作用域的,而且也是通过xml进行声明管理的

<!--
Bean对象的作用域:作用域是对象的存在范围和可见性
1.单例:singleton,默认值,表示这个对象在Spring容器中只有一个
  指定单例语法:
  <bean id="xxx" class="yyy" scope="singleton"/>
2.原型:prototype,表示每次使用getBean()都创建一个新对象
  指定语法:
  <bean id="xxx" class="yyy" scope="prototype"/>
-->
<bean id="someService" class="com.bjpowernode.service.SomeServiceImpl" scope="prototype"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值