How to solve springboot app start and shutdown immediately problem
When we develop multi-module springboot application,the layout is as follows:
1. The project layout
my-test-project
+module1
+--pom.xml
+--src
+--main
+--com
+--example
+--module1
+--domain1
+--Base1.java
+--Application.java
+module2
+--pom.xml
+--src
+--main
+--com
+--example
+--module2
+--Application.java
As you can see , module1 has a package named com.example.module1, and module2 has a package named com.example.module2, and module2 has reference to module1
2. The problem
Now in the module2, we want to use module1’s domain class, we autowire the class object like this:
MyTest.java in module2:
...
@Autowired
private Base1 base1;
add add this to module2’s Application class to expand the module2 to component scan range.
@SpringBootApplication
@ComponentScan("com.example.module1") //let the module2 to scan module1's components.
public class Application {
...
}
3. Run the app
Now run the module2, we got this exception
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.3.RELEASE)
2017-03-14 15:29:13.852 INFO 25350 --- [ main] com.example.module2.Application : Starting Module2Application on localhost with PID 25350 (started by xxx in /Users/xxx/work/xxx)
2017-03-14 15:29:13.856 DEBUG 25350 --- [ main] com.example.module2.Application : Running with Spring Boot v1.4.3.RELEASE, Spring v4.3.5.RELEASE
2017-03-14 15:29:13.856 INFO 25350 --- [ main] com.example.module2.Application : The following profiles are active: dev
2017-03-14 15:29:16.248 INFO 25350 --- [ main] com.example.module2.Application : Started Module2Application in 2.757 seconds (JVM running for 3.164)
Process finished with exit code 0
The module2 application start and exit without any exception. why?
4. The reason
Because we add componentscan range to @SpringBootApplication ,but the range is not right, the range now:
@SpringBootApplication
@ComponentScan("com.example.module1") //let the module2 to scan module1's components.
public class Application {
...
}
the range com.example.module1 is not right,because it must include the com.example.module2 package. It should be :
@SpringBootApplication
@ComponentScan("com.example") //let the module2 to scan module1's components.
public class Application {
...
}
we change the package from com.example.module1 to com.example, so it include module1 and module2 packages.
Now run test again, the exception disappeared.
You can find detail documents about the springboot here: