Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot GS: ComponentScan and ClassNotFoundException for ConnectionFactory

Tags:

I'm playing sur the Spring Boot getting started guide but the auto configuration fails and I get:

 java.lang.ClassNotFoundException: javax.jms.ConnectionFactory 

It seems it's due to the location of the Application class. Where should it be located? At the top-level package (src/main/java) or in a specific package?

like image 724
Tyler Avatar asked Jan 29 '15 09:01

Tyler


People also ask

What is @component and @ComponentScan?

@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.

When should I use ComponentScan?

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

What is @SpringBootApplication scanBasePackages?

All four of the following parameters can be used in the @SpringBootApplication annotation. scanBasePackages - Takes in a string array and allows wildcard string filtering for package names, thereby allowing entire package directories to be included or scanned.

Why do we use @ComponentScan?

@ComponentScan tells Spring in which packages you have annotated classes which should be managed by Spring. Spring needs to know which packages contain spring beans, otherwise you would have to register each bean individually in(xml file). This is the use of @ComponentScan.


2 Answers

Your Application class should be placed in a specific package and not in the default (top-level) package. For example, put it in com.example and place all your application code in this package or in sub-packages like com.example.foo and com.example.bar.

Placing your Application class in the default package, i.e. directly in src/main/java isn't a good idea and it will almost certainly cause your application to fail to start. If you do so, you should see this warning:

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package. 
like image 149
Andy Wilkinson Avatar answered Sep 19 '22 14:09

Andy Wilkinson


Do not put the bootup Application Class in default package. This will solve the problem.

Working code:

package com.spring.boot.app;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication public class App {     public static void main(String[] args) {         SpringApplication.run(App.class, args);               } } 
like image 31
Mohammed Sarfaraz Avatar answered Sep 22 '22 14:09

Mohammed Sarfaraz