Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I start with a spring boot application without the annotations componentscan,autoconfiguration,configuration,springbootapplication?

I have written some code in order test integration with mongoDB. Please find the link to the main method for running this spring boot application below,

https://github.com/siva54/simpleusercontrol/blob/master/src/main/java/com/siva/UserManagementApplication.java

From what I have read, An application should contain any of the configurations from the following URL to declare how the applications manages the context,

http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-using-springbootapplication-annotation.html

I haven't used any of those contexts, However my application works fine and I'm able to run it without any issues. Am I missing something here? Can you please help with the info of how my application is able to start and manage the context/dependencies automatically?

Thanks in advance

like image 396
daemon54 Avatar asked Mar 21 '17 04:03

daemon54


1 Answers

@SpringBootApplication is equivalent of @Configuration, @EnableAutoConfiguration and @ComponentScan. Let's consider why your application works without of any of this three annotations.

Why it works without @Configuration:

When Spring will scan packages, it will find all classes marked by @Configuration and will use them as part of configuration. But in next line you manually passed UserManagementApplication as configuration source:

SpringApplication.run(UserManagementApplication.class, args);

So spring doesn't need to find this class by scan. Therefor it is not necessary to mark it by @Configuration.


Why it works without @ComponentScan:

Class UserManagementApplication has @ImportResource("classpath:spring/application-context.xml") annotation. That means file spring/application-context.xml will be included into configuration. And this file contains next line:

<context:component-scan base-package="com.siva.*" />

So, you don't need use annotation for scan packages, because you already declared it in the xml file.


Why it works without @EnableAutoConfiguration:

This annotation allows to Spring to try guess and configure the components automatically. For example, if you include the following dependency in your build.gradle:

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-data-mongodb'
}

Spring configures all the components required to work with MongoDB automatically. And all you need just specify host and user/pass in the aplication.proprties file.

But you preferred to declare all needed beans manually in the spring/application-context.xml file. So, you simply don't need @EnableAutoConfiguration annotation at all.

like image 119
Ken Bekov Avatar answered Oct 19 '22 02:10

Ken Bekov