Where do I put my XML beans in a Spring Boot appli

2019-01-31 19:55发布

I'm getting back into Spring (currently v4). It's all wonderful now with @SpringBootApplication and the other annotations but all the documentation seems to forget to mention how I define other beans in XML!

For example I'd like to create an "SFTP Session Factory" as defined at: http://docs.spring.io/spring-integration/reference/html/sftp.html

There is a nice bit of XML to define the bean but where on earth do I put it and how do I link it in? Previously I did a:

ApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:applicationContext.xml");

to specify the file name and location but now that I'm trying to use:

ApplicationContext ctx = SpringApplication.run(Application.class);

Where do I put the XML file? Is there a magic spring name to call it?

3条回答
手持菜刀,她持情操
2楼-- · 2019-01-31 20:29

As long as you're starting with a base @Configuration class to begin with, which it maybe sounds like you are with @SpringBootApplication, you can use the @ImportResource annotation to include an XML configuration file as well.

@SpringBootApplication
@ImportResource("classpath:spring-sftp-config.xml")
public class SpringConfiguration {
  //
}
查看更多
干净又极端
3楼-- · 2019-01-31 20:31

You also can translate the XML config to a Java config. In your case it would look like:

@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;
}

You can put this method in the class with the @SpringBootApplication annotation.

查看更多
Summer. ? 凉城
4楼-- · 2019-01-31 20:31

Spring boot ideal concept is avoid xml file. but if you want to keep xml bean, you can just add @ImportResource("classPath:beanFileName.xml").

I would recommend remove the spring-sftp-config.xml file. And, convert this file to spring annotation based bean. So, whatever class has been created as bean. Just write @Service or @Component annotation before class name. for example:

XML based:

<bean ID="id name" class="com.example.Employee">

Annotation:

@Service or @Component
class Employee{
}

And, add @ComponentScan("Give the package name"). This is the best approach.

查看更多
登录 后发表回答