You have defined query method in the repository bu

2019-08-16 11:20发布

问题:

Yesterday this solution was working fine. Today I woke up to rerun the tests & it failed stating in the stacktrace that You have defined query method in the repository but you don't have any query lookup strategy defined. The infrastructure apparently does not support query methods! at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.(RepositoryFactorySupport.java:533)

As clearly shown I did not define any query methods. :-(

I'm stuck, I shall try reverting to the previous version & see where we go from there. Please help anyone can.

My Setup is as follows -->

build.gradle ->>

buildscript {
    ext {
        springBootVersion = '2.1.0.M1'
    }
    repositories {
        jcenter()
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
    dependencies {
        //Check for the latest version here: http://plugins.gradle.org/plugin/com.jfrog.artifactory
        classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4+"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6.2"

    }
}

apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "com.jfrog.artifactory"
apply plugin: 'org.sonarqube'
apply plugin: 'jacoco'


allprojects {
    apply plugin: "com.jfrog.artifactory"
}

group 'io.db'
version '1.0'
sourceCompatibility = 8 //10

configurations {
    providedRuntime
}

ext {
    springBootAdminVersion = '2.1.0-SNAPSHOT'
    springCloudVersion = 'Finchley.BUILD-SNAPSHOT'
}

repositories {
    jcenter()
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}

artifactory {
    contextUrl = "${artifactoryContextUrl}"   //The base Artifactory URL if not overridden by the publisher/resolver
    publish {
        repository {
            repoKey = 'gradle-dev-local'
            username = "${artifactoryUser}"
            password = "${artifactoryPass}"
            maven = true
        }
    }
    resolve {
        repository {
            repoKey = 'gradle-dev'
            username = "${artifactoryUser}"
            password = "${artifactoryPass}"
            maven = true
        }
    }
}

sonarqube {
    properties {
        property "sonar.projectKey", "account"
        property "sonar.projectName", "Account-Service"
        property "sonar.projectVersion", "1.0"
        property "sonar.sources", "src/main/java"
        property "sonar.language", "java"
        property "sonar.binaries", "build/classes"
        property "sonar.tests", "src/test/java"
        property "sonar.dynamicAnalysis", "reuseReports"
        property "sonar.junit.reportsPath", "build/test-reports"
        property "sonar.java.coveragePlugin", "jacoco"
        property "sonar.jacoco.reportPath", "build/test-reports/jacoco.exec"
        property 'sonar.coverage.exclusions', "io.db.accountservice.config.persistence.LiveConfig*"
    }
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-data-neo4j')
    compile('org.springframework.data:spring-data-neo4j:5.0.9.RELEASE')
    compile('org.neo4j:neo4j-ogm-bolt-driver:3.1.1-RC1')
    compile('org.neo4j:neo4j-ogm-http-driver:3.1.1-RC1')
    compile('org.springframework.boot:spring-boot-autoconfigure')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
    compile('org.springframework.cloud:spring-cloud-starter-parent:Finchley.RELEASE')
    compile('org.springframework.cloud:spring-cloud-config-client')
//    compile('org.springframework.data:spring-data-commons-core:1.4.1.RELEASE')
//    compile('org.springframework.cloud:spring-cloud-starter-openfeign')
    // https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
    // https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.0.4.RELEASE', ext: 'pom'


// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies
    compile group: 'org.springframework.cloud', name: 'spring-cloud-dependencies', version: 'Finchley.RELEASE', ext: 'pom'


    runtime('org.springframework.boot:spring-boot-devtools')

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.neo4j:neo4j-ogm-embedded-driver:3.1.1-RC1')
    testCompile('org.neo4j.test:neo4j-harness:3.4.5')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

dependencyManagement {
    imports {
        mavenBom "de.codecentric:spring-boot-admin-dependencies:${springBootAdminVersion}"
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

TestClass ->>

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class UserRepoTest {
    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(UserRepoTest.class); //ToDo: Run the tests with the Live profile to ensure stability.
    private final User user1 = new User();
    private final User user2 = new User();
    private UserRepo UserRepo;
    private List<User> userList = new ArrayList<>();

    @BeforeClass
    public static void setUp() {
        LOGGER.info("Testing Neo4j DB tests kicking off...");
    }

    @AfterClass
    public static void tearDown() {
        LOGGER.info("Testing Neo4j DB tests tearing down...");
    }

    @Before
    public void setup() {
        UserRepo.deleteAll();
        user1.setName("Sean");
        user1.setUsername("sean@test.io");
        user1.setEnabled(true);
        user1.setPassword("new-password");

        user2.setName("Steven");
        user2.setUsername("steven@test.io");
        user2.setEnabled(false);
        user2.setPassword("old-password");
        userList.add(user1);
        userList.add(user2);
    }

    @After
    public void aftermath() {
        UserRepo.deleteAll();
    }

    @Autowired
    public void setUserRepo(UserRepo UserRepo) {
        this.UserRepo = UserRepo;
    }

    @Test
    public void aSaveUserAndFindUser() {

        final User SavedUser = UserRepo.save(user1);
        final Optional<User> optionalSavedUser = Optional.of(SavedUser);

        final Optional<User> foundUser = Optional.ofNullable(UserRepo.findByUsername("sean@test.io"));

        assertTrue(optionalSavedUser.isPresent());
        LOGGER.debug("Saved UserID: " + optionalSavedUser.get().getId());
        assertNotNull("User object doesn't have an id.", optionalSavedUser.get().getId());
        assertTrue(foundUser.isPresent());
        assertTrue(user1.getUsername().equals(foundUser.get().getUsername()));
        assertTrue(user1.getName().equals(foundUser.get().getName()));
        assertTrue(user1.getPassword().equals(foundUser.get().getPassword()));
        assertTrue(foundUser.get().getEnabled());
    }
}

Application executor class:

@SpringBootApplication
@EnableEurekaClient
public class AccountRepoApp {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountRepoApp.class);
    private UserRepo userRepo;

    @Autowired
    public AccountRepoApp(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    /**
     * Spring Application launcher
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(AccountRepoApp.class, args);
    }

    /**
     * We need some initialised data to test out the live instance of the App.
     */
    @PostConstruct
    public void init() {
        userRepo.deleteAll(); //delete any pre-existing data.
        User user1 = new User(), user2 = new User();
        List<User> userList = new ArrayList<>();

        user1.setName("Sean");
        user1.setUsername("sean@test.io");
        user1.setEnabled(true);
        user1.setPassword("new-password");
        user1.setCreated(new Timestamp(new Date().getTime()));
        user1.setLastUpdated(new Timestamp(new Date().getTime()));

        user2.setName("Steven");
        user2.setUsername("steven@test.io");
        user2.setEnabled(false);
        user2.setPassword("old-password");
        user2.setCreated(new Timestamp(new Date().getTime()));
        user2.setLastUpdated(new Timestamp(new Date().getTime()));

        userList.add(user1);
        userList.add(user2);

        LOGGER.info("User-1: " + user1.toString());
        LOGGER.info("User-2: " + user2.toString());

        userRepo.saveAll(userList);
    }
}

DevConfig.java class:

@Profile("dev")
@Configuration
@EnableNeo4jRepositories(basePackages = "io.db.accountservice.repo")
@EntityScan(basePackages = "io.db.accountservice.domain")
@EnableNeo4jAuditing(setDates = true, modifyOnCreate = true)
@EnableTransactionManagement
public class DevConfig {

    @Bean
    public SessionFactory sessionFactory() {
    // with domain entity base package(s)
    return new SessionFactory(configuration(), "io.db.accountservice.domain");
}

    @Bean
    public org.neo4j.ogm.config.Configuration configuration() {
    //Note: No Config Required when in test/dev-mode.
        return new org.neo4j.ogm.config.Configuration
                .Builder()
                .build();
}

    @Bean
    public Neo4jTransactionManager transactionManager() {
        return new Neo4jTransactionManager(sessionFactory());
    }
}

User Model:

@NodeEntity
public class User {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String username;
    private String password;
    private Boolean enabled;
    @LastModifiedDate
    private Date lastUpdated;
    @CreatedDate
    private Date created;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", username='" + username + '\'' +
                ", enabled=" + enabled +
                ", lastUpdated=" + lastUpdated +
                ", created=" + created +
                '}';
    }

    // Getters & Setters
}

UserRepo.java interface:

@Repository
@RestResource(path = "users", rel = "user")
public interface UserRepo extends Neo4jRepository<User, Long> {

    User findByUsername(String username);

    User findByName(String name);
}    

Stacktrace:

java.lang.IllegalStateException: Failed to load ApplicationContext

        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
        at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
        at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountRepoApp': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo': Invocation of init method failed; nested exception is java.lang.IllegalStateException: You have defined query method in the repository but you don't have any query lookup strategy defined. The infrastructure apparently does not support query methods!
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:736)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:201)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1302)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1154)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:825)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:865)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:769)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:334)
        at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
        ... 26 more
        Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo': Invocation of init method failed; nested exception is java.lang.IllegalStateException: You have defined query method in the repository but you don't have any query lookup strategy defined. The infrastructure apparently does not support query methods!
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1743)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:290)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1132)
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:824)
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:727)
        ... 44 more
        Caused by: java.lang.IllegalStateException: You have defined query method in the repository but you don't have any query lookup strategy defined. The infrastructure apparently does not support query methods!
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:533)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:318)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$4(RepositoryFactoryBeanSupport.java:293)
        at org.springframework.data.util.Lazy.getNullable(Lazy.java:195)
        at org.springframework.data.util.Lazy.get(Lazy.java:78)
        at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:296)
        at org.springframework.data.neo4j.repository.support.Neo4jRepositoryFactoryBean.afterPropertiesSet(Neo4jRepositoryFactoryBean.java:66)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1802)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1739)
        ... 55 more

        2018-08-22 01:14:58.550  INFO 20978 --- [           main] io.db.accountservice.repo.UserRepoTest   : Testing Neo4j DB tests tearing down...
        2018-08-22 01:14:58.551  WARN 20978 --- [       Thread-4] o.n.o.d.embedded.driver.EmbeddedDriver   : Deleting temporary file store: file:/tmp/neo4j.db6708155468020884090/

        Process finished with exit code 255

回答1:

Resolved it by rolling back to the previous versions of the SpringBootVersion & the SpringCloudVersion inside the build.gradle script:

ext {
    springBootAdminVersion = '2.0.4'
    springCloudVersion = 'Finchley.SR1'
}