通过XML装配Spring的bean和高级装配
1、创建XML配置规范
spring的配置文件,需要以<beans>元素为根。
<?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-3.0.xsd
>
<!-- 添加bean -->
</beans>
2、@Profile的使用
spring并不是在构建的时候决定该创建哪一个bean,不创建哪一个bena,而是在运行的时候决定的。@Profile作用于类上,会告诉spring在何种环境下才创建。同样,在XML文件中,也可以添加profile属性。
<?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-3.0.xsd
profile="dev">
<!-- 添加bean -->
</beans>
也可以在嵌套的<beans>中添加说明。
<?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-3.0.xsd
>
<!-- 添加bean -->
<beans profile="dev">
<bean id="a" class="com.my.test.A" />
</beans>
</beans>
3、激活profile
spring确定哪个profile处于激活态,需要依赖两个独立的属性,你尽可以选择spring.profiles.active和spring.profiles.default的最佳组合方式以满足需求。
4、Spring提供了@ActiveProfiles注解,可以使用它来指定运行测试时要激活哪个profile。
5、对于有歧义的bean,比如同一个接口,好几种实现,可以用primary指定优先选择谁;
6、@Qualifier注解是使用限定符的主要方式,可以指定装配哪一个具体的bean。
7、bean的作用域
单例(Singleton),在整个应用中,只创建一个实例;
原型(Prototype),每一次注入或者通过上下文获取bean的时候,都创建一个新的bean实例
会话(Session),在Web应用中,为每个会话创建一个bean实例;
请求(Rquest):在Web应用中,为每个请求创建一个bean实例。