执行SpringBoot程序异常如下:
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itzhimei.handle.Person2' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)
at com.itzhimei.App.main(App.java:50)
... 5 more
出现类似的错误,一种可能是代码中引入了第三方jar包中的类,但是pom文件中没有引入,这种可能性较小,因为如果是这样,编辑器此时都会编译报错。
第二种可能,比如你使用的某个类是自定义的,但是在SpringBoot中没有加载到Spring的ioc容器中,此时启动SpringBoot就会报错:No qualifying bean of type ‘xxxxxx’ available。
例如我自定义了一个Person2的类,然后在主程序中做了一个测试,代码如下:
@SpringBootApplication(scanBasePackages = "com")
public class App
{
@Autowired
private SpringBootConfiguration_1 springBootConfiguration;
@Autowired
private SpringBootConfiguration_2 springBootConfiguration2;
public static void main( String[] args ) {
ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
String[] beanNamesForType = run.getBeanNamesForType(Person.class);
for(String s :beanNamesForType) {
System.out.println(s);
}
Person2 p22 = run.getBean(Person2.class);
System.out.println(p22);
}
}
问题在于Person2并没有加载到Spring的ioc容器中,需要在某个配置类中进行配置,例如:
/**
* Configuration的使用
*/
@Import({Person2.class})
@Configuration(proxyBeanMethods = false)
public class SpringBootConfiguration_3 {
@Bean
public Person person() {
return new Person();
}
}
这里我使用了@Import({Person2.class})注解把Person2加载到ioc中,此时再启动SpringBoot,打印日志如下:
person
Person2(name=null, age=0, amount=null)