I have a Spring-Boot app with a component and a scheduled function.
package My.A;
@SpringBootApplication
@EnableScheduling
public class MyApp
{
public static void main (String args []) throws Exception
{
SpringApplication.run (MyApp.class, args);
}
}
The component:
package My.A;
@Component
public class MyComp
{
@Scheduled (fixedRate = 3000)
public void foo ()
{
System.out.println ("foo");
}
}
All is fine, I get every 3s the printout of "foo".
Now I want to add JPA. It is not the 1st time I use JPA.
But it is the 1st time I have the entity in another package (My.B).
package My.B;
@Entity
@SequenceGenerator (name = "seq", initialValue = 1)
public class MyRecord
{
....
I added a Repository in App to access the DB.
package My.A;
public interface MyRecordRepo extends CrudRepository <MyRecord, Long>
{
}
And I add annotations to let MyApp find MyRecord of My.B.
package My.A;
@SpringBootApplication
@EnableScheduling
@EnableJpaRepositories ("My.B.*") // NEW
@ComponentScan (basePackages = { "My.B.*" }) // NEW
public class WebApplication
{
...
Without that MyApp would throw an exception at start that the Entity is not found. With the annotation it compiles and started fine.
But now my scheduled function foo does not get fired. I tried to add My.A.* into ComponentScan but did not work.
@ComponentScan (basePackages = { "My.B.*", "My.A.*" })
Think MyApp does not find its own component now.
How can I get my scheudled function back AND also have JPA with the class outside of my primary package?
CodePudding user response:
Add @EntityScan("My.B")
to your configuration.
When you use @ComponentScan
it disables Spring Boot auto-configuration scanning and you have to specify all the used packages manually.
Also, you don't need @EnableJpaRepositories
- Spring Boot does this automatically if it finds Spring Data JPA on the classpath.
CodePudding user response:
There is no need for .* The way component scan works is if you define only
@ComponentScan (basePackages = { "My" })
It will drill down into all subfolders of it, which includes A and B package.
But if you want to limit your scanning to specific packages then you can write
@ComponentScan (basePackages = { "My.B", "My.A" })