idea maven搭建spring報錯:No bean named 'xxx' available

lei95發表於2019-07-13

 在使用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資料夾圖示會變

相關文章