[英]@ComponentScan doesn't work in Spring boot AutoConfiguration class?
[英]Spring Boot — why doesn't the @ComponentScan work with my package combination?
我正在基於Stephan Zerhusen出色的SpringBoot + JWT演示啟動一個項目。 它可以在我的SpringToolSuite項目中安裝並正常運行。 我對此的進一步開發遇到了問題。
我想將斯蒂芬的代碼(org.zerhusen)與我的業務邏輯(com.mypackage)分開。 我嘗試過的@SpringBootApplication和@ComponentScan的配置對我來說都沒有用。
SpringBoot啟動程序是:
package org.zerhusen;
[SNIP]
@SpringBootApplication
public class JwtDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JwtDemoApplication.class, args);
}
}
如果僅將軟件包從org.zerhusen更改為com.mypackage並再次運行該程序,我會看到:
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in org.zerhusen.security.service.JwtUserDetailsServiceImpl required a bean of type 'org.zerhusen.security.repository.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'org.zerhusen.security.repository.UserRepository' in your configuration.
現在UserRepository只是一個接口:
package org.zerhusen.security.repository;
[SNIP]
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
但是該接口不是由用戶代碼實現的。 並且由於此時我僅使用H2(稍后將使用JPA和MySQL),因此該接口僅在UserDetailsService實現的實現中被引用:
package org.zerhusen.security.service;
[SNIP]
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
[SNIP]
}
有很多stackoverflow文章告訴我使用配置,但是我已經有:
@SpringBootApplication(scanBasePackages = {"org.zerhusen"})
@ComponentScan(basePackages = {"org.zerhusen"})
@EnableJpaRepositories(basePackages = {"org.zerhusen.security.repository.UserRepository"})
@EntityScan(basePackages = {"org.zerhusen"})
public class JwtDemoApplication {
[SNIP]
}
而且這些都不適合我。
我不想將所有內容強加到單個程序包樹中-如何在不重寫Stephan's的情況下將代碼與Stephan's融合? -但是我的配置無法使我的程序運行。
有人可以根據我的情況給我正確的配置嗎?
謝謝傑羅姆。
CDT 7 / 30,12: 04更新。使用注釋,我僅使用類更改了@EnableJpaRepositories語句。 進行此更改后,應用程序將正常運行。
考慮到這一點,我嘗試了變體,一次注釋了一個注釋:
我會取得成功(感謝所有響應者的支持,可正常運行的應用程序),但尚不明白為什么需要這四個注釋。
問題出在您的@EnableJpaRepositories
中-您指定了類名而不是包名 。 只需完全刪除參數(實際上,您應該能夠消除除@SpringBootApplication
所有內容, @SpringBootApplication
包括@ComponentScan
)。
通常,Boot的默認值是一個很好的通用折衷方案,因此,除非您與默認值發生實際沖突,否則不要開始明確指定內容。
在您的@EnableJpaRepositories
,可以使用basePackagesClass
而不是basePackages
或設置org.zerhusen.security.repository
如果您希望保留basePackages
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.