Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'user' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:892)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1318)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1132)
at com.example.SpringbootEnableApplication.main(SpringbootEnableApplication.java:25)
在使用Springboot的自动注入@AutoWired时,有时会出现注入失败,显示没有这个bean加载。
此时我们可以有多种解决方法:
这里给出三种:
1:@ComponentScan("com.example.config") 使用ComponentScan注解,该注解内是你需要扫描类所在的包的位置

2:第二种是使用@Import(UserConfig.class) 注解,Import中填入你所需要导入的类,个人认为这种方式暴力直接,好用。
3:第三种是自定义注解封装,可以自定义一个你所需要注入的类,将你所需要注入的类导入注解中,再直接使用该注解即可。这种方法,大大提高开发的复用性。

自定义EnableUser注解,之后需要使用的地方直接使用注解方式即可。@EnableUser

三种方式,可自行选择。
当在Springboot应用中遇到@Autowired注入失败,显示无bean定义时,可以尝试使用@ComponentScan指定扫描包,@Import导入特定配置类,或者创建自定义注解来封装注入逻辑,提高代码复用性。
9801

被折叠的 条评论
为什么被折叠?



