简体   繁体   English

将Spring XML配置转换为Java配置

[英]Translate Spring XML configuration to Java config

I'd like to use Spring with Java configuration, but almost all examples are writte in XML and I don't know how to translate them to Java. 我想使用Spring配置Java,但几乎所有的例子都是用XML编写的,我不知道如何将它们翻译成Java。 Look at these examples from Spring Security 3 : 查看Spring Security 3中的这些示例

 <http auto-config='true'>
   <intercept-url pattern="/**" access="ROLE_USER" />
 </http> 

 <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

  <password-encoder hash="sha">
    <salt-source user-property="username"/>
  </password-encoder>

How could this translated to Java config? 怎么能转换成Java配置? Or, more generally, how can I translate Spring XML config to Java? 或者,更一般地说,如何将Spring XML配置转换为Java? There is a little section about Java confing in the Spring reference but it is not that helpful. 在Spring参考中有一些关于Java confing的部分,但它并没有那么有用。

按照JavaConfig项目文档

This is probably more simple than you think. 这可能比你想象的更简单。 Spring isn't doing any magic. 春天没有做任何魔术。 The XML config parser just creates bean definitions and registers them with the bean factory. XML配置解析器只创建bean定义并将其注册到bean工厂。 You can do the same by creating a DefaultListableBeanFactory and registering your bean definitions with it. 您可以通过创建DefaultListableBeanFactory并使用它注册bean定义来执行相同的操作。 The main mistake here is to think "gee, I'll just create the beans and put them in the app context". 这里的主要错误是认为“哎呀,我只是创建bean并将它们放在app环境中”。 This approach doesn't work because Spring creates beans lazily and the API is built around the idea of a factory that gets called when necessary, not a factory which does all the work at startup. 这种方法不起作用,因为Spring懒洋洋地创建bean,而API是围绕工厂的想法构建的,在必要时调用它,而不是在启动时完成所有工作的工厂。

Here is some example code . 这是一些示例代码 Note that this sample needs a lot more lines of code but by defining your own helper methods, you should be able to break this down to something which should be on par with XML. 请注意,此示例需要更多代码行,但通过定义自己的帮助程序方法,您应该能够将其分解为与XML相同的内容。

Also check the source for the Spring unit tests for examples. 另请查看Spring单元测试源代码示例。

You can't translate XML configurations with custom namespaces (such as http://www.springframework.org/schema/security ). 您无法使用自定义命名空间(例如http://www.springframework.org/schema/security )转换XML配置。 However, you can mix XML configurations with Java-based using @ImportResource 但是,您可以使用@ImportResource将XML配置与基于Java的配置混合使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM