Spring之Config小结

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声明与加载:

  1. 在配置文件中嵌套配置文件
  2. 在注解中嵌套配置注解
  3. 在注解中嵌套配置文件的引入。
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值