我有一個帶有組件和預定功能的 Spring-Boot 應用程式。
package My.A;
@SpringBootApplication
@EnableScheduling
public class MyApp
{
public static void main (String args []) throws Exception
{
SpringApplication.run (MyApp.class, args);
}
}
組件:
package My.A;
@Component
public class MyComp
{
@Scheduled (fixedRate = 3000)
public void foo ()
{
System.out.println ("foo");
}
}
一切都很好,我每 3 秒列印一次“foo”。
現在我想添加 JPA。這不是我第一次使用 JPA。
但這是我第一次將物體放在另一個包(My.B)中。
package My.B;
@Entity
@SequenceGenerator (name = "seq", initialValue = 1)
public class MyRecord
{
....
我在 App 中添加了一個存盤庫來訪問資料庫。
package My.A;
public interface MyRecordRepo extends CrudRepository <MyRecord, Long>
{
}
并且我添加了注釋讓 MyApp 找到 My.B 的 MyRecord。
package My.A;
@SpringBootApplication
@EnableScheduling
@EnableJpaRepositories ("My.B.*") // NEW
@ComponentScan (basePackages = { "My.B.*" }) // NEW
public class WebApplication
{
...
沒有那個 MyApp 會在開始時拋出一個例外,即找不到物體。使用注釋,它可以編譯并正常啟動。
但是現在我的預定函式 foo 沒有被解雇。我嘗試將 My.A.* 添加到 ComponentScan 中,但沒有成功。
@ComponentScan (basePackages = { "My.B.*", "My.A.*" })
Think MyApp 現在找不到自己的組件。
我怎樣才能讓我的 scheudled 函式回來,并且在我的主包之外還有 JPA 類?
uj5u.com熱心網友回復:
添加@EntityScan("My.B")到您的配置中。
當你使用@ComponentScan它時,它會禁用 Spring Boot 自動配置掃描,你必須手動指定所有使用的包。
此外,您不需要@EnableJpaRepositories- 如果 Spring Boot 在類路徑上找到 Spring Data JPA,它會自動執行此操作。
uj5u.com熱心網友回復:
不需要 .* 組件掃描的作業方式是,如果您只定義
@ComponentScan (basePackages = { "My" })
它將深入到它的所有子檔案夾,其中包括 A 和 B 包。
但是如果你想限制你的掃描到特定的包,那么你可以寫
@ComponentScan (basePackages = { "My.B", "My.A" })
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478766.html
上一篇:JPQL問題更新記錄
