@Autowired不适用于 Spring-Data 中的存储库 (NullPointerException)

@Autowired not working for repositories in Spring-Data (NullPointerException)

提问人:Лев Сабуров 提问时间:7/10/2022 最后编辑:DevilsHnd - 退したЛев Сабуров 更新时间:7/10/2022 访问量:110

问:

我有一个java(9.0.4)项目,其中包含spring-data。

pom.xml 中的依赖关系:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.21</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>9.4.0.jre8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.21</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

Конфигуратор:

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import java.util.Properties;

@Configuration
@ComponentScan("ru.tenderwin")
@EnableJpaRepositories("ru.tenderwin")
public class DataConfig {

    @Bean
    public DriverManagerDataSource TWDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(com.microsoft.sqlserver.jdbc.SQLServerDriver.class.getName());
        dataSource.setUrl("url");
        dataSource.setUsername("name");
        dataSource.setPassword("password");

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emFactory = new LocalContainerEntityManagerFactoryBean();
        emFactory.setDataSource(TWDataSource());
        emFactory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        emFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties jpaProperties = new Properties();
        //jpaProperties.setProperty("show_sql", "true");
        //jpaProperties.setProperty("hibernate.format_sql", "true");
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect");
        //jpaProperties.setProperty("hibernate.current_session_context_class", "thread");
        //jpaProperties.setProperty("hibernate.format_sql", "true");

        emFactory.setJpaProperties(jpaProperties);
        emFactory.setPackagesToScan("ru.tenderwin");

        return  emFactory;
    }

    @Bean
    public JpaTransactionManager transactionManager(){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

}

本质:

import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(schema = "Schema")
public class Clients {

    @Id
    @GeneratedValue
    private String ID;
    @Column
    private String Name;
    @Column
    private Timestamp RegistrationDate;

    public Clients() {
    }

    @Override
    public String toString() {
        return "Clients{" +
                "ID='" + ID + '\'' +
                ", Name='" + Name + '\'' +
                ", RegistrationDate=" + RegistrationDate +
                '}';
    }
}

存储 库:

import org.springframework.data.repository.CrudRepository;
import ru.tenderwin.TWdata.models.TWIdentity.Clients;

public interface ClientsRepository extends CrudRepository<Clients,String> {

}

我正在尝试将数据从数据库提取到实体中,并将其输入到控制台中:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.tenderwin.TWdata.repositories.TWIdentity.ClientsRepository;

@ContextConfiguration(classes = DataConfig.class)
@Transactional
public class Main {

    @Autowired
    public ClientsRepository clientsRepository;

    @Test
    void testers() {
        System.out.println(
                clientsRepository.findById("DE39596D-2890-4D91-BE24-000D480190AE")
        );
    }
    
}

这会导致错误:

java.lang.NullPointerException 在 ru.tenderwin.Main.testers(Main.java:20) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:564) 在 org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) 在 org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) 在 org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) 在 org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) 在 org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) 在 org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) 在 org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) 在 org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) 在 org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) 在 org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) 在 org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) 在 org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) 在 org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) 在 org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) 在org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) 在 java.base/java.util.ArrayList.forEach(ArrayList.java:1380) 在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorSer副.java:41) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) 在org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) 在 java.base/java.util.ArrayList.forEach(ArrayList.java:1380) 在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) 在org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) 在org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) 在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) 在 org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) 在 org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) 在 org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229) 在 org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197) 在org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211) 在 org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191) 在 org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128) 在 com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) 在 com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) 在 com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) 在com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

进程已完成,退出代码为 -1

但是,有趣的是,如果您通过从上下文中请求存储库来显示实体,那么就不会有问题:

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
import ru.tenderwin.TWdata.DataConfig;
import ru.tenderwin.TWdata.repositories.TWIdentity.ClientsRepository;

@ContextConfiguration(classes = DataConfig.class)
@Transactional
public class Main {

    @Test
    void testers() {
        ApplicationContext context = new
                AnnotationConfigApplicationContext(DataConfig.class);


        System.out.println(
                context.getBean(ClientsRepository.class).
                        findById("DE39596D-2890-4D91-BE24-000D480190AE")
        );
    }

}

我们的客户端显示在控制台中:

可选[Clients{ID='DE39596D-2890-4D91-BE24-000D480190AE', Name='Неизвестный клиент', RegistrationDate=2022-02-06 07:24:10.8759664}]

我完全无法弄清楚为什么@Autowired不适用于我的存储库

java nullpointerexception spring-data

评论

1赞 cigien 7/10/2022
欢迎来到 Stack Overflow!本网站上发布的所有内容都必须以英文为准。请翻译您的帖子。

答: 暂无答案