Spring配置信息
所有的Spring Bean信息都是定義在Config文件或者Configuration的配置類中的。
例如:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
引入配置
在Configuration註解的配置類中,還可以繼續引入其他的配置類或者配置文件。本小節將對其中做總結分析。
@Import(XXXConfig.class)
使用說明:
後面跟隨的是Java Config class,等同於配置文件聲明瞭一個Bean.
@Configuration
public class AnotherConfig {
@Bean
public AnotherBean anotherBean() {
return new AnotherBean();
}
}
-------------------------------
@Configuration
@Import(AnotherConfig.class)
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
<beans>
<bean name="myBean" class="com.xx.xxx.MyBean" />
</beans>
@ImportSource(“classpath:xxx-spring-bean.xml”)
其功能等同於引入了一個Spring bean的定義文件。其在實際使用中,等同於在配置文件中:
<import resource="spring-bean.xml" />
例如:
@Configuration
@ImportSource("classpath:spring-bean.xml")
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="anotherBean"
class="com.xxx.xxx.AntherBean">
</bean>
</beans>
其相當於在AppConfig配置Bean中引入了AnotherBean的聲明與定義。
總結
在Spring中可以支持基於配置文件和基於註解的Bean聲明與引入。同時支持以下形式的Bean聲明與加載:
- 在配置文件中嵌套配置文件
- 在註解中嵌套配置註解
- 在註解中嵌套配置文件的引入。