前言
場景:將一些公共的方法封裝成了一個jar包,在其他項目中進行引用的時候報錯
報錯原因:bean沒有注入,引進來的jar包沒有被spring管理,因為類沒有被@Service,@Repository等類注解,如果我們想用@Autowired注入也會報錯
示例:
@Autowired public UserService userService;
報錯:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.lib.user.UserService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
解決方式(1)
創建配置類使用@Bean注解進行注入類。
@Configuration public class UserServiceConfig { @Bean UserService getUserService(){ UserService userService = new UserService(); return userService; } }
解決方式(2)
在啟動類加上掃描注解@ComponentScan("/")
//手動加上@ComponentScan注解並指定那個bean所在的包 //@ComponentScan 的作用就是根據定義的掃描路徑,把符合掃描規則的類裝配到spring容器中 @ComponentScan(basePackages={"com.util.user"}) @SpringBootApplication public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication .class, args); } }