2017-02-02 8 views
0

У меня возникла проблема с правильной настройкой базы данных H2 в springboot + hibernate и очень понравилась бы вам. Я думаю, что моя проблема заключается в @Transaction Annotation, так как соответствующий класс генерирует исключение NullPointerException. Вот некоторая справочная информация:Настройка базы данных H2 в Spring + Hibernate без файла XML дает NullPointerException

  • Идея программы (которая еще не законченный) является то, что агенты (класс «AgentLogic») могут calulate цены для выполнения конкретных задач в рамках системы Multi-Agent. Чтобы рассчитать цену, агент выводит параметры из базы данных. Эти параметры необходимы для некоторых алгоритмов машинного обучения (в классе «MachineLearningSource»), которые будут вычислять цену агента.

  • Я хотел бы настроить конфигурацию базы данных без использования XML-файла, подобно тому, например, в http://www.baeldung.com/hibernate-4-spring

  • Проект имеет следующую структуру:

Project Structure

ОБНОВЛЕННЫЙ КОД ПОСЛЕ ПРИНЦИПИАЛЬНЫХ ИЗМЕНЕНИЙ ИЗ @ СТАНИСЛАВЛ

проект реализован в SpringBoot. Соответственно, я использую следующий класс Application:

package org.schlago.mldb; 
import... 

@SpringBootApplication 
public class Application { 

    public static void main(String[] args) { 

     // ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); 
     SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class); 
     builder.headless(false); 
     ConfigurableApplicationContext context = builder.run(args); 
     } 
    } 

Следующий класс содержит конфигурацию базы данных в Spring Hibernate, названный DataBaseConfig:

package org.schlago.mldb.database; 

import... 
@Configuration 
@Profile("param_db") 
@EnableTransactionManagement 
@ComponentScan({"org.schlago.mldb.mapping","org.schlago.mldb.machineLearning"}) 
public class DatabaseConfig { 

    @Autowired 
    private Environment env; 

    @Bean 
    public DataSource dataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(env.getProperty("datasource.driver")); 
     dataSource.setUrl(env.getProperty("datasource.url")); 
     dataSource.setUsername(env.getProperty("datasource.username")); 
     dataSource.setPassword(env.getProperty("datasource.password")); 
     return dataSource; 
    } 

    @Bean 
    public LocalSessionFactoryBean sessionFactory(){ 
     LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); 
     sessionFactoryBean.setDataSource(dataSource()); 
     sessionFactoryBean.setPackagesToScan(env.getProperty("entitymanager.packagesToScan")); 
     Properties hibernateProperties = new Properties(); 
     hibernateProperties.put("hibernate.dialect", env.getProperty("jpa.hibernate.dialect")); 
     hibernateProperties.put("hibernate.show_sql", env.getProperty("jpa.hibernate.show-sql")); 
     hibernateProperties.put("hibernate.hbm2ddl.auto", env.getProperty("jpa.hibernate.hbm2ddl.auto")); 
     hibernateProperties.put("spring.jpa.hibernate.ddl-auto", env.getProperty("jpa.hibernate.ddl-auto")); 
     sessionFactoryBean.setHibernateProperties(hibernateProperties); 
     return sessionFactoryBean; 
    } 

    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){ 
     HibernateTransactionManager transactionManager = new HibernateTransactionManager(); 
     transactionManager.setSessionFactory(sessionFactory); 

     return transactionManager; 
    } 

    @Bean 
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { 
     return new PersistenceExceptionTranslationPostProcessor(); 
    } 

} 

Эта конфигурация использует следующую среду (@Profile) в порядок для настройки sessionFactoryBean, называется appliation.yaml:

spring.profiles: param_db 
datasource: 
    driver: org.h2.Driver 
    url: jdbc:h2:tcp://localhost/~/test 
    username: sa 
    password: 
jpa: 
    hibernate.show-sql: true 
    hibernate.hbm2ddl.auto: none 
    hibernate.dialect: org.hibernate.dialect.H2Dialect 
    hibernate.ddl-auto: validate 
    hibernate.globally_quoted_identifiers: true 
entitymanager: 
    packagesToScan: org.schlago.mldb.mapping 

Параметры должны быть вставлены в базу данных через DAO, используя @Trans аннотация. Это DAO называется ParametersDao:

package org.schlago.mldb.mapping; 
import ... 

@Transactional 
public class ParametersDao { 

    @Autowired 
    private SessionFactory _sessionFactory; 

    private Session getSession() { 
     return _sessionFactory.getCurrentSession(); 
    } 

    public void save(Parameters parameters) { getSession().save(parameters); } 

    public void update(Parameters parameters) { 
     getSession().update(parameters); 
    } 

    public List<Parameters> getAllParameters() { 
     return getSession().createQuery("from Parameters").list(); 
    } 

    public Parameters getParameterById(int id) { 
     List<Parameters> parametersList = getSession() 
       .createQuery("from Parameters where paramId = :theId") 
       .setParameter("theId", id).list(); 
     if (parametersList.size() == 0) { 
      return null; 
     } 
     return parametersList.get(0); 
    } 
} 

Параметры задаются с помощью класса Paramters:

package org.schlago.mldb.mapping; 

@Entity 
@Table(name = "mlparam") 
public class Parameters { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long paramId; 

    @Column(name = "name") 
    private String name; 

    @Column(name = "value") 
    private double value; 

    @Column(name = "timestamp") 
    private Date timestamp; 

    public Parameters(){ 
    } 

    public long getParamId() { 
     return paramId; 
    } 

    public void setParamId(int paramId) { 
     this.paramId = paramId; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public double getValue() { 
     return value; 
    } 

    public void setValue(double value) { 
     this.value = value; 
    } 

    public Date getTimestamp() { 
     return timestamp; 
    } 

    public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } 
} 

Я думаю, что есть ошибка в пути ParametersDao является установка. Однако для вашего лучшего понимания здесь используются другие классы, используемые в этом проекте. Следующий класс - AgentLogic, который будет вычислять цену по запросу в более позднем странном коде. Так как код все еще находится в ранней стадии, я использовал @PostConstruct, а не запрос, чтобы проверить, если цена calulation работы:

package org.schlago.mldb.logic; 

import... 

    @Component 
public class AgentLogic { 

    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); 

    @Autowired 
    private MachineLearningSource machineLearningSource; 

    @PostConstruct 
    public void init(){ 

     int priceInCent = 50; 
     priceInCent = machineLearningSource.getPrice(getAgent()); 
     LOGGER.info("Answered with offer about " + priceInCent + " Cents."); 

    } 

    // DUMMY class: Return a new agent 
    public static Agent getAgent(){ 

     // Currently, an Agent is just an (empty) dummy class 
     Agent agent = new Agent(); 
     return agent; 
    } 
} 

Наконец, следующий класс отвечает за цены calcuation. Поскольку код все еще находится на ранней стадии, расчет цены устанавливается случайным образом, а не выполняется алгоритмы машинного обучения.В методе getParameters(), некоторые параметры вводятся в базу данных для целей тестирования:

package org.schlago.mldb.machineLearning; 

import org.schlago.mldb.Nodes.Agent; 
import org.schlago.mldb.mapping.Parameters; 
import org.schlago.mldb.mapping.ParametersDao; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 

import java.util.Date; 
import java.util.HashMap; 
import java.util.Random; 

    @Component 
public class MachineLearningSource { 

    @Autowired 
    ParametersDao parametersDao; 

    private static final Logger LOGGER = LoggerFactory.getLogger(MachineLearningSource.class); 

    public int getPrice(Agent agent) { 
     Random r = new Random(); 
     int thePrice = r.nextInt(99) + 1; 
     LOGGER.info("The price is dynamically calculated right now!"); 
     HashMap<String, Double> parameters = getParameters(); 

     return thePrice; 
    } 

    public HashMap<String, Double> getParameters() { 
     HashMap<String, Double> equationParameters = new HashMap<>(); 

     // TEST: Since database is currently empty, parameters are inserted manually here (this will change later) 
     LOGGER.info("About to insert into table"); 

     Parameters myCalcParams = new Parameters(); 
     myCalcParams.setName("kappa"); 
     myCalcParams.setValue(2.39583992); 
     myCalcParams.setTimestamp(new Date()); 

     parametersDao.save(myCalcParams); 

     LOGGER.info("Successfully inserted parameters"); 


     /* 
     // Get the parameters via parametersDao, work in progress! 
     List<Parameters> parameters = parametersDao.getAllParameters(); 

     Parameters myParam = parametersDao.getParameterById(3748); 
     if (myParam == null) { 
      LOGGER.info("Dataset does not exist!"); 
     } 

     for (Parameters param : parameters) { 
      equationParameters.put(param.getName(), param.getValue()); 
      LOGGER.info("Actual parameter for price calculation: " + param.getName()); 
      LOGGER.info("Value: " + param.getValue()); 
     } 
     */ 


     // TEST: Return dummy equationParameters 
     equationParameters.put("a", 2.48238948239); 
     equationParameters.put("b", 8.23482489729); 

     return equationParameters; 
    } 

} 

ОБНОВЛЕНО ОШИБКА ЗАЯВЛЕНИЕ

Unfortuntely, я все еще получаю ошибку:

2017-02-03 14:41:39.005 INFO 7416 --- [   main] org.schlago.mldb.Application    : Starting Application on mobile-97 with PID 7416 (C:\Users\Jan\Documents\Masterarbeit\12_MLDBtest\target\classes started by Jan in C:\Users\Jan\Documents\Masterarbeit\12_MLDBtest) 
2017-02-03 14:41:39.005 INFO 7416 --- [   main] org.schlago.mldb.Application    : The following profiles are active: param_db 
2017-02-03 14:41:39.083 INFO 7416 --- [   main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]79ca92b9: startup date [Fri Feb 03 14:41:39 CET 2017]; root of context hierarchy 
2017-02-03 14:41:40.581 INFO 7416 --- [   main] trationDelegate$BeanPostProcessorChecker : Bean 'databaseConfig' of type [class org.schlago.mldb.database.DatabaseConfig$$EnhancerBySpringCGLIB$$829d3967] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 
2017-02-03 14:41:40.721 INFO 7416 --- [   main] o.s.j.d.DriverManagerDataSource   : Loaded JDBC driver: org.h2.Driver 
2017-02-03 14:41:41.004 INFO 7416 --- [   main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 
2017-02-03 14:41:41.020 INFO 7416 --- [   main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ 
    name: default 
    ...] 
2017-02-03 14:41:41.129 INFO 7416 --- [   main] org.hibernate.Version     : HHH000412: Hibernate Core {4.3.11.Final} 
2017-02-03 14:41:41.129 INFO 7416 --- [   main] org.hibernate.cfg.Environment   : HHH000206: hibernate.properties not found 
2017-02-03 14:41:41.129 INFO 7416 --- [   main] org.hibernate.cfg.Environment   : HHH000021: Bytecode provider name : javassist 
2017-02-03 14:41:41.394 INFO 7416 --- [   main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final} 
2017-02-03 14:41:41.521 INFO 7416 --- [   main] org.hibernate.dialect.Dialect   : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect 
2017-02-03 14:41:41.693 INFO 7416 --- [   main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory 
2017-02-03 14:41:42.363 INFO 7416 --- [   main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export 
2017-02-03 14:41:42.432 INFO 7416 --- [   main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete 
2017-02-03 14:41:42.510 WARN 7416 --- [   main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'agentLogic': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.schlago.mldb.machineLearning.MachineLearningSource org.schlago.mldb.logic.AgentLogic.machineLearningSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'machineLearningSource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.schlago.mldb.mapping.ParametersDao org.schlago.mldb.machineLearning.MachineLearningSource.parametersDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.schlago.mldb.mapping.ParametersDao] 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)} 
2017-02-03 14:41:42.510 INFO 7416 --- [   main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 
2017-02-03 14:41:42.510 INFO 7416 --- [   main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export 
2017-02-03 14:41:42.559 INFO 7416 --- [   main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete 
2017-02-03 14:41:42.559 ERROR 7416 --- [   main] o.s.boot.SpringApplication    : Application startup failed 

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'agentLogic': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.schlago.mldb.machineLearning.MachineLearningSource org.schlago.mldb.logic.AgentLogic.machineLearningSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'machineLearningSource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.schlago.mldb.mapping.ParametersDao org.schlago.mldb.machineLearning.MachineLearningSource.parametersDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.schlago.mldb.mapping.ParametersDao] 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)} 

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.schlago.mldb.machineLearning.MachineLearningSource org.schlago.mldb.logic.AgentLogic.machineLearningSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'machineLearningSource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.schlago.mldb.mapping.ParametersDao org.schlago.mldb.machineLearning.MachineLearningSource.parametersDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.schlago.mldb.mapping.ParametersDao] 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)} 

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'machineLearningSource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.schlago.mldb.mapping.ParametersDao org.schlago.mldb.machineLearning.MachineLearningSource.parametersDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.schlago.mldb.mapping.ParametersDao] 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)} 

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.schlago.mldb.mapping.ParametersDao org.schlago.mldb.machineLearning.MachineLearningSource.parametersDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.schlago.mldb.mapping.ParametersDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: 

2017-02-03 14:41:42.575 INFO 7416 --- [   main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/charsets.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/deploy.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/access-bridge-64.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/cldrdata.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/dnsns.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/jaccess.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/jfxrt.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/localedata.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/nashorn.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/sunec.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/sunjce_provider.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/sunmscapi.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/sunpkcs11.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/ext/zipfs.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/javaws.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/jce.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/jfr.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/jfxswt.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/jsse.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/management-agent.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/plugin.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/resources.jar, file:/C:/Program%20Files/Java/jdk1.8.0_60/jre/lib/rt.jar, file:/C:/Users/Jan/Documents/Masterarbeit/12_MLDBtest/target/classes/, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.3.5.RELEASE/spring-boot-starter-data-jpa-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-starter/1.3.5.RELEASE/spring-boot-starter-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot/1.3.5.RELEASE/spring-boot-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.3.5.RELEASE/spring-boot-autoconfigure-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.3.5.RELEASE/spring-boot-starter-logging-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/ch/qos/logback/logback-classic/1.1.7/logback-classic-1.1.7.jar, file:/C:/Users/Jan/.m2/repository/ch/qos/logback/logback-core/1.1.7/logback-core-1.1.7.jar, file:/C:/Users/Jan/.m2/repository/org/slf4j/jul-to-slf4j/1.7.21/jul-to-slf4j-1.7.21.jar, file:/C:/Users/Jan/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.21/log4j-over-slf4j-1.7.21.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-core/4.2.6.RELEASE/spring-core-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.3.5.RELEASE/spring-boot-starter-aop-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-aop/4.2.6.RELEASE/spring-aop-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/Users/Jan/.m2/repository/org/aspectj/aspectjweaver/1.8.9/aspectjweaver-1.8.9.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.3.5.RELEASE/spring-boot-starter-jdbc-1.3.5.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.0.33/tomcat-jdbc-8.0.33.jar, file:/C:/Users/Jan/.m2/repository/org/apache/tomcat/tomcat-juli/8.0.33/tomcat-juli-8.0.33.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-jdbc/4.2.6.RELEASE/spring-jdbc-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.11.Final/hibernate-entitymanager-4.3.11.Final.jar, file:/C:/Users/Jan/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/C:/Users/Jan/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar, file:/C:/Users/Jan/.m2/repository/org/hibernate/hibernate-core/4.3.11.Final/hibernate-core-4.3.11.Final.jar, file:/C:/Users/Jan/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/C:/Users/Jan/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar, file:/C:/Users/Jan/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/C:/Users/Jan/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/C:/Users/Jan/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.5.Final/hibernate-commons-annotations-4.0.5.Final.jar, file:/C:/Users/Jan/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/C:/Users/Jan/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/C:/Users/Jan/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/data/spring-data-jpa/1.9.4.RELEASE/spring-data-jpa-1.9.4.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/data/spring-data-commons/1.11.4.RELEASE/spring-data-commons-1.11.4.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-orm/4.2.6.RELEASE/spring-orm-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-context/4.2.6.RELEASE/spring-context-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-expression/4.2.6.RELEASE/spring-expression-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-tx/4.2.6.RELEASE/spring-tx-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-beans/4.2.6.RELEASE/spring-beans-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.21/jcl-over-slf4j-1.7.21.jar, file:/C:/Users/Jan/.m2/repository/org/springframework/spring-aspects/4.2.6.RELEASE/spring-aspects-4.2.6.RELEASE.jar, file:/C:/Users/Jan/.m2/repository/com/sparkjava/spark-core/1.1.1/spark-core-1.1.1.jar, file:/C:/Users/Jan/.m2/repository/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-server/9.2.16.v20160414/jetty-server-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-http/9.2.16.v20160414/jetty-http-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-util/9.2.16.v20160414/jetty-util-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-io/9.2.16.v20160414/jetty-io-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-webapp/9.2.16.v20160414/jetty-webapp-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-xml/9.2.16.v20160414/jetty-xml-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-servlet/9.2.16.v20160414/jetty-servlet-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/org/eclipse/jetty/jetty-security/9.2.16.v20160414/jetty-security-9.2.16.v20160414.jar, file:/C:/Users/Jan/.m2/repository/net/sf/xenqtt/xenqtt/0.9.7/xenqtt-0.9.7.jar, file:/C:/Users/Jan/.m2/repository/org/json/json/20151123/json-20151123.jar, file:/C:/Users/Jan/.m2/repository/com/pi4j/pi4j-core/1.0/pi4j-core-1.0.jar, file:/C:/Users/Jan/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar, file:/C:/Users/Jan/.m2/repository/org/bouncycastle/bcpkix-jdk15on/1.54/bcpkix-jdk15on-1.54.jar, file:/C:/Users/Jan/.m2/repository/com/h2database/h2/1.4.192/h2-1.4.192.jar, file:/C:/Users/Jan/.m2/repository/org/opcfoundation/ua/1.02.337.10/ua-1.02.337.10.jar, file:/C:/Users/Jan/.m2/repository/com/prosys/ua/server-client-sdk/2.2/server-client-sdk-2.2.jar, file:/C:/Program%20Files%20(x86)/JetBrains/IntelliJ%20IDEA%202016.2.5/lib/idea_rt.jar] 

ответ

0

Попробуйте добавить @Component аннотации к классу обслуживания MachineLearningSource и проверить как dao, так и сервис включены в @ComponentScan

UPDATE

В AgentLogic вручную создать machineLearningSource

MachineLearningSource machineLearningSource = new MachineLearningSource(); 
    priceInCent = machineLearningSource.getPrice(getAgent()); 

Вместо добавления

@Autowired 
private MachineLearningSource machineLearningSource; 

Для класса, чтобы Spring инициализировать это правильно. Или вы можете autowire дао в классе и вручную вызвать

machineLearningSource.setDao(theAutowiredDao); 

UPDATE2:

Теперь дао не маркирован быть обнаружен как весенний боба. Добавить @Repository аннотация для DAO.

Update3:

sessionFactoryBean.setPackagesToScan(env.getProperty("entitymanager.packagesToScan")); 

проверка, какие именно пакеты проверяются там. Необходимо иметь все пакеты, в которых хранятся классы сущностей.

+0

Большое спасибо за ваш отзыв @StanislavL. Я сделал так, как вы предположили: я добавил '@ Component' в MachineLearningSource и явно установил' @ComponentScan ({"org.schlago.mldb.mapping", "org.schlago.mldb.machineLearning"}) '. К сожалению, я все равно получаю ту же ошибку; Параметры Dao, кажется, Null ... – schlago

+0

Ответ обновлен. Пожалуйста, проверьте – StanislavL

+0

Большое спасибо @StanislavL. Это очень хороший момент. Я обновил свой код и, соответственно, обновил код, указанный в моем вопросе выше. Однако теперь я получаю другой тип сообщения об ошибке. Тем не менее, ядро ​​оператора - если я получил это право - это то, что параметры Dao не инициируются ... – schlago