Spring перезаписывает объекты в коллекции

Доброго времени суток!

Ситуация в следующем: Есть класс Word с двумя стринговыми полями (код упрощен до самой сути)

public class Word{

private String targetWord;
private String description;

//getters, setters etc...

}

И класс в котором храниться коллекция экземпляров Word с методом Add который добавляет объект в коллекцию

public class Dictionary{

private ArrayList<Word> wordList;


public Dictionary(ArrayList<Word> wordList) {
    this.wordList = wordList;
}

public void addWord(Word word) {
    wordList.add(word); 
}

//etc...

}

В метод addWord объект поступает уже с инициализированными полями.

И наконец есть сервиc в который инъектятся зависимости и в котором вызывается вышеуказанный метод Dictionary.addWord

@Component
public class DictionaryService {

private final Dictionary dictionary;
private Word wordEntity;

public DictionaryService(Dictionary dictionary, Word wordEntity) {
    this.dictionary = dictionary;
    this.wordEntity = wordEntity;
}


 public void addWord(String word, String description){

    wordEntity.setTargetWord(word);
    wordEntity.setDescription(description);

    System.out.println(wordEntity.hashCode());

    if (checkWord(wordEntity) {
        dictionary.addWord(wordEntity);
    }
    
}

Но когда отрабатывает метод addWord то в коллекции перезаписываются все уже записанные ранее объекты на идентичные последнему

класс Main

@Configuration
@ComponentScan
public class Main {


@Bean
Dictionary dictionary(){
    return new Dictionary();
}



@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Word word(){
    return new Word();
}

public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
    ReaderAndView reader = context.getBean(ReaderAndView.class);
    reader.start();

}

}


Ответы (1 шт):

Автор решения: denis Krivorutchko
@Component
public class DictionaryService {

private final Dictionary dictionary;
//Ваш сервис хранит сылку на обькт Word wordEntity
// а он должен создавать новый обжект типа Word 
// и в методе addWord сетить уже новую сылку

private Word wordEntity;

public DictionaryService(Dictionary dictionary, Word wordEntity) {
  
    this.dictionary = dictionary;
    this.wordEntity = wordEntity;
}


 public void addWord(String word, String description){

  Word newWord = new Word ();
  newWord.setTargetWord(word);
  newWord.setDescription(description);

    

    System.out.println(wordEntity.hashCode());

    if (checkWord(wordEntity) {
        dictionary.addWord(wordEntity);
    }
    
}
→ Ссылка