Форум программистов, компьютерный форум, киберфорум
Java: Spring, Spring Boot
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
0 / 0 / 0
Регистрация: 12.11.2011
Сообщений: 97

Spring и ошибка внедрения класса

23.01.2014, 22:31. Показов 1509. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день,возможно я ошибся разделом,если так то приношу свои извинения и прошу направить в правильном направлении,а теперь собственно сам вопрос.
Есть два класса
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.work.Spring.Dao;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
 
import org.springframework.stereotype.Repository;
 
import com.work.Interfaces.jpaDao;
import com.work.Model.Reminder;
 
/**
 * 
 * @author Sergey Borovskiy
 * Класс реализует интерфейс jpaDao и является одной из реализаций для класса Reminder
 */
 
@Repository("JpaReminder")
public class JpaReminder extends jpaDao<Reminder>
{
    private EntityManager em;
    
    /**
     * @return Возвращает entityManager
     */
    @Override
    protected EntityManager getEntityManager() 
    {
        return em;
    }
 
    public EntityManager getEm() 
    {
        return em;
    }
 
    @PersistenceContext(unitName = "TaskTracker")
    public void setEm(EntityManager em) 
    {
        this.em = em;
    }
 
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.work.Spring.mainClass;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.work.Interfaces.dbService;
import com.work.Model.Reminder;
import com.work.Spring.Dao.JpaReminder;
 
@Service("ReminderService")
public class ReminderService implements dbService<Reminder> 
{
    @Autowired
    private JpaReminder jpaReminder;
 
    @Transactional
    public List<Reminder> getAll() 
    {
        return jpaReminder.findAll();
    }
 
    @Transactional
    public Reminder get(Object id) 
    {
        return jpaReminder.find(id);
    }
 
}
В конфигурации всё правильно и остальная часть приложения тоже работает на ура,загвостка собственно в чём,почему то не хочет создавать jpaReminder bean,ругается на то что он пытаеться проскочить раньше чем нужно и тем самым вызывает ошибку,как такового решения в интернете я не нашёл,по крайне мере не одно не подошло.Если убрать из контекста spring jpaReminder и убрать внедрение его в класс ReminderService,всё работает на ура,что подтверждает что проблема именно в классе jpaReminder.
Есть у кого нибудь какие нибудь идеи,пробовал вместо contextPersistent всё делать через autowired,не помогло.На всякий случай скину весь код приложения
Вложения
Тип файла: zip Spring.zip (3.51 Мб, 2 просмотров)
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
23.01.2014, 22:31
Ответы с готовыми решениями:

Проекты внедрения ERP систем с открытым кодом - есть ли внедрения в России?
Добрый вечер. Интересует информация о внедрениях в России ERP-систем с открытым кодом, в идеале от участников внедрения, руководителей...

Spring MVC. 404 ошибка при включении Spring Data JPA в проект
Добрый день. Есть простой шаблонный проект с использованием Spring MVC и Maven. С зависимостями Spring MVC проект собирается нормально и...

Ошибка внедрения dataSource
Привет! Подскажи, пожалуйста, в чем может быть проблема? бин dataSource не внедряется в классе UserRepositoryImpl. Вот сам класс ...

2
0 / 0 / 0
Регистрация: 12.11.2011
Сообщений: 97
24.01.2014, 13:43  [ТС]
И конечно же,забыл выкинуть код ошибки,извините)
Exception in thread "main" org.springframework.beans.factory.BeanCr eationException: Error creating bean with name 'ReminderService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCr eationException: Could not autowire field: private com.work.Spring.Dao.JpaReminder com.work.Spring.mainClass.ReminderServic e.jpaReminder; nested exception is org.springframework.beans.factory.BeanCr eationException: Error creating bean with name 'JpaReminder' defined in file [/home/qwerty/Eclipse/Spring/target/classes/com/work/Spring/Dao/JpaReminder.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiat ionException: Could not instantiate bean class [com.work.Spring.Dao.JpaReminder]: Constructor threw exception; nested exception is java.lang.ArrayIndexOutOfBoundsException : 1
at org.springframework.beans.factory.annota tion.AutowiredAnnotationBeanPostProcesso r.postProcessPropertyValues(AutowiredAnn otationBeanPostProcessor.java:287)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.pop ulateBean(AbstractAutowireCapableBeanFac tory.java:1106)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.doC reateBean(AbstractAutowireCapableBeanFac tory.java:517)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.cre ateBean(AbstractAutowireCapableBeanFacto ry.java:456)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory$1.getObject(Abstra ctBeanFactory.java:294)
at org.springframework.beans.factory.suppor t.DefaultSingletonBeanRegistry.getSingle ton(DefaultSingletonBeanRegistry.java:22 5)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:291)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory.getBean(AbstractBe anFactory.java:193)
at org.springframework.beans.factory.suppor t.DefaultListableBeanFactory.preInstanti ateSingletons(DefaultListableBeanFactory .java:609)
at org.springframework.context.support.Abst ractApplicationContext.finishBeanFactory Initialization(AbstractApplicationContex t.java:918)
at org.springframework.context.support.Abst ractApplicationContext.refresh(AbstractA pplicationContext.java:469)
at org.springframework.context.support.Clas sPathXmlApplicationContext.<init>(ClassP athXmlApplicationContext.java:139)
at org.springframework.context.support.Clas sPathXmlApplicationContext.<init>(ClassP athXmlApplicationContext.java:83)
at com.work.Spring.App.main(App.java:22)
Caused by: org.springframework.beans.factory.BeanCr eationException: Could not autowire field: private com.work.Spring.Dao.JpaReminder com.work.Spring.mainClass.ReminderServic e.jpaReminder; nested exception is org.springframework.beans.factory.BeanCr eationException: Error creating bean with name 'JpaReminder' defined in file [/home/qwerty/Eclipse/Spring/target/classes/com/work/Spring/Dao/JpaReminder.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiat ionException: Could not instantiate bean class [com.work.Spring.Dao.JpaReminder]: Constructor threw exception; nested exception is java.lang.ArrayIndexOutOfBoundsException : 1
at org.springframework.beans.factory.annota tion.AutowiredAnnotationBeanPostProcesso r$AutowiredFieldElement.inject(Autowired AnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annota tion.InjectionMetadata.inject(InjectionM etadata.java:87)
at org.springframework.beans.factory.annota tion.AutowiredAnnotationBeanPostProcesso r.postProcessPropertyValues(AutowiredAnn otationBeanPostProcessor.java:284)
... 13 more
Caused by: org.springframework.beans.factory.BeanCr eationException: Error creating bean with name 'JpaReminder' defined in file [/home/qwerty/Eclipse/Spring/target/classes/com/work/Spring/Dao/JpaReminder.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiat ionException: Could not instantiate bean class [com.work.Spring.Dao.JpaReminder]: Constructor threw exception; nested exception is java.lang.ArrayIndexOutOfBoundsException : 1
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.ins tantiateBean(AbstractAutowireCapableBean Factory.java:997)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.cre ateBeanInstance(AbstractAutowireCapableB eanFactory.java:943)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.doC reateBean(AbstractAutowireCapableBeanFac tory.java:485)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.cre ateBean(AbstractAutowireCapableBeanFacto ry.java:456)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory$1.getObject(Abstra ctBeanFactory.java:294)
at org.springframework.beans.factory.suppor t.DefaultSingletonBeanRegistry.getSingle ton(DefaultSingletonBeanRegistry.java:22 5)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:291)
at org.springframework.beans.factory.suppor t.AbstractBeanFactory.getBean(AbstractBe anFactory.java:193)
at org.springframework.beans.factory.suppor t.DefaultListableBeanFactory.findAutowir eCandidates(DefaultListableBeanFactory.j ava:876)
at org.springframework.beans.factory.suppor t.DefaultListableBeanFactory.doResolveDe pendency(DefaultListableBeanFactory.java :818)
at org.springframework.beans.factory.suppor t.DefaultListableBeanFactory.resolveDepe ndency(DefaultListableBeanFactory.java:7 35)
at org.springframework.beans.factory.annota tion.AutowiredAnnotationBeanPostProcesso r$AutowiredFieldElement.inject(Autowired AnnotationBeanPostProcessor.java:478)
... 15 more
Caused by: org.springframework.beans.BeanInstantiat ionException: Could not instantiate bean class [com.work.Spring.Dao.JpaReminder]: Constructor threw exception; nested exception is java.lang.ArrayIndexOutOfBoundsException : 1
at org.springframework.beans.BeanUtils.inst antiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.suppor t.SimpleInstantiationStrategy.instantiat e(SimpleInstantiationStrategy.java:76)
at org.springframework.beans.factory.suppor t.AbstractAutowireCapableBeanFactory.ins tantiateBean(AbstractAutowireCapableBean Factory.java:990)
... 26 more
Caused by: java.lang.ArrayIndexOutOfBoundsException : 1
at com.work.Interfaces.jpaDao.<init>(jpaDao .java:24)
at com.work.Spring.Dao.JpaReminder.<init>(J paReminder.java:19)
at sun.reflect.NativeConstructorAccessorImp l.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImp l.newInstance(NativeConstructorAccessorI mpl.java:57)
at sun.reflect.DelegatingConstructorAccesso rImpl.newInstance(DelegatingConstructorA ccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstanc e(Constructor.java:532)
at org.springframework.beans.BeanUtils.inst antiateClass(BeanUtils.java:147)
... 28 more

Суть ошибки опять же как я и говорил выше в том что не может создать jpaReminder bean,есть идеи)
0
 Аватар для Skipy
2000 / 1427 / 92
Регистрация: 25.11.2010
Сообщений: 3,611
24.01.2014, 15:51
А можно посмотреть на конструктор класса com.work.Interfaces.jpaDao? Конкретно - на строку 24?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
24.01.2014, 15:51
Помогаю со студенческими работами здесь

Ошибка внедрения типа взаимодействия
Всем привет. Подскажите, что я делаю неправильно, что у меня возникает ошибка: Ошибка 1 Внедрение типа взаимодействия...

Spring - Как сделать Autowired в N объектах класса
Подскажите пожалуйста как правильно сделать. Есть класс ImagesPool, он создается через new и его всегда существует несколько экземпляров. В...

Как Spring узнаёт о классе инициализирующим диспетчера согласно конфигурационного класса?
Доброго времени! Объясните пожалуйста, как Spring узнаёт о классе инициализирующего диспетчера запросов (WebAppInitializer) согласно...

Ошибка со spring
Помогите решить проблему с spring framework &quot;C:\Program Files\Java\jdk1.8.0_192\bin\java.exe&quot; &quot;-javaagent:C:\Program...

Spring. Ошибка автосвязывания
Возникает следующие ошибки. На форумах полно таких случаев, но решения не подошли для моего случая. Предполагаю, проблема где-то из двух...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru