在使用idea maven搭建spring的时候,仅有几行代码和配置(spring配置放在resource下),且都没有错情况下,启动依然报错
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'xxx' available
package com.demo;
import com.demo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
// 1、加载spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:spring.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
userService.add();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.demo.service.UserService"/>
</beans>
在main方法中用的是classpath的形式加载spring配置文件,会出现这种报错的情况。这是因为idea没有eclipse对maven的支持好。解决办法:右键resource文件夹选择Mark Directory as > Resources Root
resource文件夹图标会变