工厂类
![](https://img.haomeiwen.com/i11541496/356d8cce10f42227.png)
使用的接口是:ApplicationContext,老版本所采用的是BeanFactory
使用的实现类是:
- FileSystemXmlApplicationContext 当xml配置文件不在工程内
- ClassPathXmlApplicationContext 当xml配置文件在工程内的
三种实例化Bean的方式
- 使用类构造器实例化(默认无参数)
//xml配置文件
<bean id="bean1" class="com.demo1.Bean1"></bean>
//Bean1类文件
public class Bean1 {
public Bean1() {
System.out.println("Bean1被创建了");
}
}
- 使用静态工厂方法实例化(简单工厂模式)
//xml配置文件
<bean id="bean2" class="com.demo1.Bean2StaticFactory" factory-method="getBean2"></bean>
//Bean2类文件
public class Bean2 {
}
//静态工厂
public class Bean2StaticFactory {
public static Bean2 getBean2(){
System.out.println("Bean2实例创建成功 ");
return new Bean2();
}
}
- 使用实例工厂方法实例化(工厂方法模式)
//xml配置文件
<bean id="bean3Factory" class="com.demo1.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
//Bean3类文件
public class Bean3 {
}
//工厂
public class Bean3Factory {
public Bean3 getBean3(){
System.out.println("Bean3被实例化");
return new Bean3();
}
}
Bean的配置
- id和name
- 一般情况下,装配一个Bean时,通过指定一个id属性作为Bean的名称
- id属性在IOC容器中必须是唯一的
- 如果Bean的名称中含有特殊字符,就需要使用name属性
- class
- class用于设置一个类的完全路径名称,主要作用是IOC容器生成类的实例
Bean的作用域
在xml配置文件中的bean标签下,用scope属性来设置
类别 | 说明 |
---|---|
singleton | 在SpringIOC容器中仅存在一个Bean实例,Bean以单实例的方式存在 |
prototype | 每次调用getBean()时都会返回一个新的实例 |
request | 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境 |
session | 同一个HTTP session共享一个Bean,不同的HTTP Session使用不同的Bean。该作用域仅适用于WebApplicationContext环境 |
Spring中Bean的生命周期
Spring初始化bean或销毁bean时,有时需要做一些处理工作,因此spring可以在创建和销毁bean的时候调用bean的两个生命周期方法
<bean id="XXX" class="..xxx" init-method="init" destory-method="destroy" />
//这里的init,destroy是任意的,自定义的
//想要执行销毁时,需要关闭工厂
((ClassPathXmlApplicationContext) applicationContext).close();
当bean被载入到容器的时候调用init
当bean从容器中删除的时候调用destroy(scope=singleton有效)
==web容器中会自动调用,但是main函数或测试用例需要手动调用==
Spring完整的声明周期
![](https://img.haomeiwen.com/i11541496/1f44237d6f2282a3.png)
- instantiate bean对象实例化
- populate properties封装属性
- 如果Bean实现BeanNameAware执行setBeanName
- 如果Bean实现BeanFactoryAware或者ApplicationContextAware设置工厂setBeanFactory或者上下文对象setApplicationContext
- ==如果存在类实现BeanPostProcessor(先处理Bean),执行postProcessBeforeInitialization==
- 如果Bean实现InitializingBean执行afterPropertiesSet
- 调用<bean init-method="init">指定初始化方法init
- ==如果存在类实现BeanPostProcessor(后理Bean),执行postProcessAfterInitialization==
- 执行业务处理
- 如果Bean实现DisposableBean执行destroy
- 调用<bean destory-method="customerDestroy">指定销毁方法customerDestroy
注:可以使用第五步或第八步来加强方法,这里的类需要注册bean,只需有class属性即可
Spring的属性注入
对于类成员变量,注入方式有三种
- 构造函数注入
- 属性setter方法注入
接口注入
==Spring支持前两种==
构造函数注入
//User类
public class User {
private String name;
private String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
}
//xml配置文件
<bean id="user" class="com.demo2.User">
<constructor-arg name="name" value="王花花"/>
<constructor-arg name="age" value="20"/>
</bean>
属性setter方法注入
//User类
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
//xml配置文件
<bean id="user" class="com.demo2.User">
<property name="name" value="王花花"></property>
<property name="age" value="20"></property>
</bean>
==当类的成员变量中出现对象时==,不使用value使用ref:
//xml配置文件
<bean id="user" class="com.demo2.User">
<property name="name" value="王花花"></property>
<property name="age" value="20"></property>
<property name="cat" ref="cat"></property>
</bean>
<bean id="cat" class="com.demo2.Cat">
<property name="name" value="花花"></property>
<property name="age" value="2"></property>
</bean>
p名称空间的属性注入
- 为了简化XML文件配置,Spring从2.5开始引入一个新的p名称空间
- 语法规则
//首先引入p命名空间
<beans
xmlns:p="http://www.springframework.org/schema/p">
</beans>
p:<属性名>="xxx" //引入常量值
p:<属性名>-ref="xxx" //引用其他Bean对象
同上面的例子
//首先引入p命名空间
<beans
xmlns:p="http://www.springframework.org/schema/p">
</beans>
<bean id="user" class="com.demo2.User" p:name="王花花" p:age="20" p:cat-ref="cat"/>
<bean id="cat" class="com.demo2.Cat" p:name="花花" p:age="2"/>
SpEL属性注入
SpEl:spring expression language, spring表达式语言,对依赖注入进行简化
语法:#{表达式}
<bean id="" value="#{表达式}">
使用字符串:#{'hello'}
使用另一个bean:#{beanId}
使用指定名属性,并使用方法:#{beanId.content.toUpperCase()}
使用静态字段或方法:#{T(java.lang.Math).PI}
使用SpEL注入对象属性时,也使用value,不使用ref
复杂类型的属性注入
- 数组类型
<bean id="xxx" class="xxx">
<property name="arrs">
<list>
<value>11</value>
<value>22</value>
</list>
</property>
</bean>
- List集合类型
<bean id="xxx" class="xxx">
<property name="list">
<list>
<value>11</value>
<value>22</value>
</list>
</property>
</bean>
- Set集合类型
<bean id="xxx" class="xxx">
<property name="set">
<set>
<value>11</value>
<value>22</value>
</set>
</property>
</bean>
- Map集合类型
<bean id="xxx" class="xxx">
<property name="map">
<map>
<entry key="a" vlaue="1"/>
<entry key="b" vlaue="2"/>
</map>
</property>
</bean>
- 属性类型
<bean id="xxx" class="xxx">
<property name="properties">
<props>
<prop key="username">root</prop>
<prop key="password">1234</prop>
</props>
</property>
</bean>
使用注解定义Bean
Spring2.5引入使用注解去定义Bean
- @Component描述Spring框架中Bean
//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"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean definitions here -->
<!-- 开始注解扫描 -->
<context:component-scan base-package="包路径" />
</beans>
//bean类中
@Component("user") //id
public class User(){
}
除了@Component外,Spring提供了3个功能基本和@Component等效的注解
- @Repository用于对DAO实现类进行标注
- @Service用于对Service实现类进行标注
- @Controller用于对Controller实现类进行标注
这三个注解是为了让标注类本身的用途清晰,Spring在后续版本会对其增强
注解方式注入属性
- 注入一般字符串属性,使用@Value("值")
@Value("王花花")
private String name;
//有setter时写在setter上
@Value("王花花")
public void setName(String name) {
this.name = name;
}
- 使用@Autowired进行自动注入
- @AutoWired默认按照类型进行注入,如果存在两个相同Bean类型,则按照名称注入
- @AutoWired注入时可以针对成员变量或者set方法
- 通过@Autowired的required属性,设置一定要找到匹配的Bean
- 使用@Qualifier指定注入Bean的名称
- 使用Qualifier指定Bean名称后,注解Bean必须指定相同名称
@Autowired
@Qualifier("personDao")
- Spring提供对JSR-250中定义@Resource标准注解的支持
//等同于上面Autowired两行
@Resource(name = "personDao")
Spring的其他注解
- Spring初始化
@PostConstruct
- 销毁
//仅当scope为singleton时有效
@PreDestroy
- 作用范围
//默认是singleton
@Scope("")
XML配置和注解配置混合使用
XMl的优势
- 结构清晰,易于阅读
注解的优势
- 开发便捷,属性注入方便
XMl与注解的整合开发
- 引入context命名空间
- 在配置文件中添加context:annotation-config标签
<context:annotation-config />
网友评论