0

I am a newbee in Spring and problem happend when i write a case about prototype and singleton

here is the code

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;
    }

}

here is the component

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();
    }
}

and here is the JAVAconfig

after that is the test case

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());
    }

}

and the problem happened

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.springinaction.chapter_3.beanScope.Notepad' available: expected single matching bean but found 2: notepad,SingleNotepad

Shouldn't Spring only componentScan the @Component?

Subash
  • 7,098
  • 7
  • 44
  • 70

0 Answers0