간단한 웹 응용 프로그램을 개발하려고하지만 웹 프런트 엔드에서 실수의 가능성을 모두 배제하기 위해 명령 프롬프트에서 실행하는 작은 클래스를 작성했습니다 .최대 절전 모드를 통해 데이터베이스에 액세스하려고 시도한 후 NullPointerException이 발생했습니다.
package org.vadim.testmvc;
import org.vadim.testmvc.model.*;
import org.vadim.testmvc.service.*;
public class TestMain {
public static void main(String[] args){
Strings s = new Strings();
TestService ts = new TestService();
s.setText("StrText");
ts.addStrings(s);
System.out.println(ts.listStrings());
}
}
TestService.java (그들은 원래 목록에 존재해야하지만, import 문없이) :
package org.vadim.testmvc.service;
@Service
public class TestService implements TestServiceInterface {
//@Autowired
TestDAO testdao = new TestDAO();
@Transactional
public List<Strings> listStrings(){
return testdao.listStrings();
}
@Transactional
public void addStrings(Strings strings){
testdao.addStrings(strings);
}
}
TestDAO.java :
package org.vadim.testmvc.dao;
@Transactional
@Repository
public class TestDAO implements TestDAOInterface {
@Autowired
private SessionFactory sessionFactory;
public void addStrings(Strings strings){
sessionFactory.getCurrentSession().save(strings);
}
@SuppressWarnings("unchecked")
public List<Strings> listStrings(){
return sessionFactory.getCurrentSession().createQuery("from Strings").list();
}
}
엔티티 클래스 :
package org.vadim.testmvc.model;
@Entity
@Table(name="STRINGS")
public class Strings {
@Id
@Column(name="ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name="TEXT")
private String text;
public void setId(Integer id){
this.id=id;
}
public Integer getId(){
return id;
}
public String getText(){
return text;
}
public void setText(String text){
this.text=text;
}
}
hibernate.cfg.xm L :
Exception in thread "main" java.lang.NullPointerException
at org.vadim.testmvc.dao.TestDAO.listStrings(TestDAO.java:23)
at org.vadim.testmvc.service.TestService.listStrings(TestService.java:18)
at org.vadim.testmvc.TestMain.main(TestMain.java:11)
동일한 께 :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="org.vadim.testmvc.model.Strings"/>
</session-factory>
</hibernate-configuration>
루트의 context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config/>
<context:component-scan base-package="org.vadim.testmvc.dao"/>
<context:component-scan base-package="org.vadim.testmvc.service"/>
<import resource="data.xml"/>
</beans>
인 data.xml는
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
</props>
</property>
</bean>
</beans>
이 예외 만남 후 스택 트레이스이고 TestDAO.addStrings를 실행하려고하면 발생합니다. (문자열 문자열) 메서드는, 즉 문제가 listStrings() 반환 결과가 아니라 데이터베이스에 액세스 할 수 있습니다. mysql 명령 프롬프트에서 일부 항목을 추가하여 비어 있지 않게하려고 시도했습니다. 나는 그것을 성공하지만 그것이 프로그램의 행동에 영향을 미치지는 않았다. 여기
그냥 당신이@Autowired
을 주석 이유
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.vadim.testmvc.dao.TestDAO org.vadim.testmvc.service.TestService.testdao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.vadim.testmvc.dao.TestDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.vadim.testmvc.dao.TestDAO org.vadim.testmvc.service.TestService.testdao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.vadim.testmvc.dao.TestDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.vadim.testmvc.dao.TestDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 23 more
확인 모든 것이 신선하게 배포 할의) 현재 세션 이는 SessionFactory.openSession을 (사용할 수를 얻을 수 doesnot. 예외는 DAO가 스프링 빈으로 인식되지 않는다는 것을 의미하지만 @Repository – Bozho