栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

了解spring @Configuration类

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

了解spring @Configuration类

将XML迁移到

@Configuration

@Configuration
只需几个步骤即可将xml迁移到:

  1. 创建一个带
    @Configuration
    注释的类:
@Configurationpublic class MyApplicationContext {}
  1. 为每个
    <bean>
    标签创建一个方法,其注释为
    @Bean
@Configurationpublic class MyApplicationContext {  @Bean(name = "someBean")  public SomeClass getSomeClass() {    return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty  }  @Bean(name = "anotherBean")  public AnotherClass getAnotherClass() {    return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse  }}
  1. 为了导入,
    beanFromSomewhereElse
    我们需要导入它的定义。可以用XML定义它,我们将使用
    @importResource
@importResource("another-application-context.xml")@Configurationpublic class MyApplicationContext {  ...  }

如果bean是在另一个

@Configuration
类中定义的,则可以使用
@import
注释:

@import(OtherConfiguration.class)@Configurationpublic class MyApplicationContext {  ...}
  1. 导入其他XML或
    @Configuration
    类之后,可以通过在
    @Configuration
    类中声明私有成员来使用它们在上下文中声明的bean ,如下所示:
@Autowired@Qualifier(value = "beanFromSomewhereElse")private final StrangeBean beanFromSomewhereElse;

或者用它直接作为在其中定义了取决于该豆的方法参数beanFromSomewhereElse使用@Qualifier如下:

@Bean(name = "anotherBean")public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) {  return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse);}
  1. 导入属性与从另一个xml或
    @Configuration
    类导入bean非常相似。除了使用,
    @Qualifier
    我们将使用
    @Value
    以下属性:
@Autowired@Value("${some.interesting.property}")private final String someInterestingProperty;

这也可以与SpEL表达式一起使用。

  1. 为了允许spring将此类视为bean容器,我们需要通过将以下标记放在上下文中在主xml中对其进行标记:
<context:annotation-config/>

现在,你可以导入

@Configuration
与创建简单bean完全相同的类:

<bean />

有一些方法可以完全避免使用Spring XML,但是它们不在此答案的范围内。你可以在我基于其答案的博客文章中找到这些选项之一。

使用此方法的优缺点

基本上,由于一些优势,我发现这种声明bean的方法比使用XML更舒适。

  1. Typos - @Configuration
    类已编译,拼写错误将不允许编译
  2. Fail fast (compile time)
    -如果你忘记注入Bean,则会在编译时失败,而不是像XML那样在运行时失败
  3. Easier to navigate in IDE
    -在bean的构造函数之间了解依赖关系树。
  4. 可以轻松调试配置启动

正如我所看到的那样,缺点并不多,但我可以想到一些缺点:

  1. 滥用 -代码比XML更容易滥用
  2. 使用XML,你可以基于在编译时不可用但在运行时提供的类定义依赖项。使用
    @Configuration
    类时,必须在编译时提供可用的类。通常这不是问题,但是在某些情况下可能是这样。
    底线:在你的应用程序上下文中结合XML
    @Configuration
    和注释是完全可以的。Spring并不关心使用bean声明的方法。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号