最近一直在学习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"/>