我是春天的新人 当我写一个关于原型和单例的案例时会发生问题
这是代码
package com.springinaction.chapter_3.beanScope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* Created by sha0w on 17-3-22.
*/
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Notepad {
private String notepadText;
public String getNotepadText() {
return notepadText;
}
public String insertNotepadText(String insert) {
return notepadText += insert;
}
}
这是组件
package com.springinaction.chapter_3.beanScope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
/**
* Created by sha0w on 17-3-22.
*/
@ComponentScan(basePackages = "com.springinaction.chapter_3.beanScope")
@Configuration
public class NotepadConfig {
@Bean(name = "SingleNotepad")
public Notepad _notepad() {
return new Notepad();
}
}
这是JAVAconfig
之后是测试用例
package com.springinaction.chapter_3.beanScope;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by sha0w on 17-3-22.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = NotepadConfig.class)
public class notePadTest {
@Autowired
private
Notepad notepad_1;
@Autowired
private
Notepad notepad_2;
private AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(NotepadConfig.class);
private Notepad notepad_3 = (Notepad) annotationConfigApplicationContext.getBean("SingleNotepad");
private Notepad notepad_4 = (Notepad) annotationConfigApplicationContext.getBean("SingleNotepad");
@Test
public void scopeTest() {
notepad_1.insertNotepadText("1.cnm");
notepad_2.insertNotepadText("2.cnm");
notepad_3.insertNotepadText("3.cnm");
notepad_4.insertNotepadText("4.cnm");
System.out.println(notepad_1.getNotepadText());
System.out.println(notepad_2.getNotepadText());
System.out.println(notepad_3.getNotepadText());
System.out.println(notepad_4.getNotepadText());
}
}
并且问题发生了
引起:org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有'com.springinaction.chapter_3.beanScope.Notepad'类型的限定bean可用:预期的单个匹配bean但找到2:notepad,SingleNotepad
不应该仅Spring组件扫描@Component吗?