初學Spring,“No bean named 'beanScope' is defined”這個問題困擾了我好幾個小時,查資料無果后,重寫好幾遍代碼后發現問題居然是配置文件不能放在包里。。。要放在src的直接目錄下。。。心碎了一地。。。
使用的是 windows 10 / eclipse 4.5.2 /Spring-framework-4.3.0/
下面是我的Spring學習代碼:
第一步:下載Spring的jar文件,傳送門:http://repo.spring.io/milestone/org/springframework/ 找到想要的版本后點擊下載
第二步:去tomcat官網下載commonts-logging.jar文件,這是使用Spring必須的jar包,傳送門:http://commons.apache.org/proper/commons-logging/
因為我用了junit做測試,就也要去下載junit.jar啦,github里面就可以下載:https://github.com/junit-team/junit4/wiki/Download-and-Install,注意哦,在這個頁面除了下載junit.jar還要下載hamcrest-core.jar包,同時加入項目才會生效。
第三步:導入相關jar包,我導入的有:
第四步:新建一個bean類,代碼如下
package com.demo.bean; public class BeanScope { public void say() { System.out.println("BeanScope say : " + this.hashCode()); } }
第五步:新建一個xml配置文件spring-beanscope,代碼如下:
<?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="beanScope" class="com.demo.bean.BeanScope" scope="singleton"></bean> </beans>
第六步:新建一個測試基類UnitTestBase,代碼如下:
package com.demo.test.base; import org.junit.Before; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.StringUtils; public class UnitTestBase { private ApplicationContext context; private String springXmlpath; public UnitTestBase() {} public UnitTestBase(String springXmlpath) { this.springXmlpath = springXmlpath; } @Before public void before() { if (StringUtils.isEmpty(springXmlpath)) { springXmlpath = "classpath*:spring-*.xml"; } try { context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+")); } catch (BeansException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") protected <T extends Object> T getBean(String beanId) { try { return (T)context.getBean(beanId); } catch (BeansException e) { e.printStackTrace(); return null; } } protected <T extends Object> T getBean(Class<T> clazz) { try { return context.getBean(clazz); } catch (BeansException e) { e.printStackTrace(); return null; } } }
第七步:新建一個測試類TestBeanScope,代碼如下:
package com.demo.test.bean; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import com.demo.bean.BeanScope; import com.demo.test.base.UnitTestBase; @RunWith(BlockJUnit4ClassRunner.class) public class TestBeanScope extends UnitTestBase { public TestBeanScope() { super("classpath*:spring-beanscope.xml"); } @Test public void testSay() { BeanScope beanScope = super.getBean("beanScope"); beanScope.say(); } }
最后執行成功!注意配置文件不能放在包里,要直接放在src目錄下,否則會報錯:No bean named 'beanScope' is defined
最后,當時這個問題困擾了我好久,搞得我搜了好多資料,發現了一個不錯的Spring學習平台,推薦一下,哈哈哈:http://www.tutorialspoint.com/spring/index.htm