[英]Where do I put my XML beans in a Spring Boot application?
我要回到Spring(目前是第4版)。 现在使用@SpringBootApplication
和其他注释都很精彩,但所有文档似乎都忘了提及我如何在XML中定义其他bean!
例如,我想创建一个“SFTP Session Factory”,如下所示: http : //docs.spring.io/spring-integration/reference/html/sftp.html
有一些很好的XML来定义bean,但我在哪里放置它以及如何将其链接? 以前我做了一个:
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
指定文件名和位置,但现在我正在尝试使用:
ApplicationContext ctx = SpringApplication.run(Application.class);
我在哪里放置XML文件? 是否有一个神奇的春天名称来称呼它?
只要你开始使用基本的@Configuration
类,它可能听起来像是@SpringBootApplication
,你也可以使用@ImportResource
注释来包含XML配置文件。
@SpringBootApplication
@ImportResource("classpath:spring-sftp-config.xml")
public class SpringConfiguration {
//
}
您还可以将XML配置转换为Java配置。 在你的情况下,它看起来像:
@Bean
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost("localhost");
factory.setPrivateKey(new ClassPathResource("classpath:META-INF/keys/sftpTest"));
factory.setPrivateKeyPassphrase("springIntegration");
factory.setPort(22);
factory.setUser("kermit");
return factory;
}
您可以使用@SpringBootApplication
批注将此方法放在类中。
Spring启动的理想概念是避免使用xml文件。 但是如果你想保留xml bean,你可以添加@ImportResource("classPath:beanFileName.xml")
。
我建议删除spring-sftp-config.xml
文件。 并且,将此文件转换为基于spring注释的bean。 所以,无论什么类都被创建为bean。 只需在类名之前编写@Service
或@Component
注释。 例如:
基于XML:
<bean ID="id name" class="com.example.Employee">
注解:
@Service or @Component
class Employee{
}
并且,添加@ComponentScan("Give the package name")
。 这是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.