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声明与加载:
- 在配置文件中嵌套配置文件
- 在注解中嵌套配置注解
- 在注解中嵌套配置文件的引入。