0

In Spring Framework is it possible to eliminate the entire Spring.xml and use a configuration class with @Configuration and @Bean annotation for creating bean, and for all other purpose use a spring.xml?

George
  • 2,860
  • 18
  • 31
  • 1
    Sure why not ... But why... It if works slowly migrate it to @Configuraition. Just use `@ImportResource` to import the original xml file and use it together with `@Configuration`. – M. Deinum Sep 28 '18 at 12:33
  • Yup, this has been in spring for some time. Here's a decent article http://www.robinhowlett.com/blog/2013/02/13/spring-app-migration-from-xml-to-java-based-config/ – Taylor Sep 28 '18 at 13:45
  • refer to answer in https://stackoverflow.com/questions/14594303/maven-3-archetype-for-project-with-spring-spring-mvc-hibernate-jpa/18049397#18049397 – AzizSM Sep 28 '18 at 14:12

2 Answers2

0

Yes, you can have pure java configuration in Spring. You have to create a class and annotate it with @Configuration. We annotate methods with @Bean and instantiate the Spring bean and return it from that method.

@Configuration
public class SomeClass {

     @Bean
     public SomeBean someBean() {
         return new SomeBean();
     }
}

If you want to enable component scanning, then you can give @ComponentScan(basePackages="specify_your_package") under the @Configuration. Also the method name as someBean serves as bean id. Also if you have to inject a dependency, you can use constructor injection and do as following:

@Configuration
public class SomeClass {

     @Bean
     public SomeDependency someDependency() {
         return new SomeDependency();
     }

     @Bean
     public SomeBean someBean() {
         return new SomeBean(someDependency());
     }
}
Navjot Singh
  • 678
  • 7
  • 18
0

Yes,most of (maybe all of)official guides uses absolutely no xml configuration file,just annotations.

Jin.H
  • 36
  • 1