Spring Data JPA: org.springframework.beans.factory.UnsatisfiedDependencyException: - PullRequest
0 голосов
/ 15 мая 2018

Я пытаюсь добавить переменную crossOrigin в файл Application.property.и доступ к этой переменной через контроллер, используя @value, он работает для следующих двух конечных точек, но когда я добавляю @value к третьей конечной точке, я получаю следующее сообщение об ошибке

AccountController.java

@RestController
@RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account")
public class AccountController {

    @Autowired
    AccountService accService;

    @Value("${crossOrigin}")
    @GetMapping("/loadAcctLocationList")
    public ResponseEntity<List<Account>> findLocation() {
        return  ResponseEntity.ok(accService.findLocation());
    }

}

TestAccountController

@RunWith(SpringRunner.class)
public class TestAccountController {

    private MockMvc mockMvc;

    @Mock
    private AccountService accountService;

    @InjectMocks
    private AccountController accountController;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
    }

    @Test
    public void findLocationTest() throws Exception {

        Account account = new Account();
        account.setsLocation("Test1");

        List<Account> accountObj = new ArrayList<Account>();
        accountObj.add(account);    

        Mockito.when(accountService.findLocation()).thenReturn(accountObj);

        mockMvc.perform(get("/spacestudy/$ InstituteIdentifier/admin/account/loadAcctLocationList"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].sLocation", is("Test1")))
                .andExpect(jsonPath("$.*",Matchers.hasSize(1)));    

        for(Account result: accountObj) {

            assertEquals("Test1", result.sLocation);

        }

        }

application.properties

crossOrigin =@CrossOrigin(origins ="http://localhost:4200")
server.port=8086
spring.datasource.url=jdbc:postgresql://localhost/SpaceStudyDB
spring.datasource.username=postgres
spring.datasource.password=postgres

Консоль

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-15 01:59:17.915 ERROR 5240 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController': Unsatisfied dependency expressed through method 'btnSaveClick' parameter 0; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:667) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at com.spacestudy.SpaceStudyAdminAccountMaintenance.main(SpaceStudyAdminAccountMaintenance.java:10) [classes/:na]
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:74) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1093) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:307) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:109) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 23 common frames omitted

Может кто-нибудь сказать мне, что я делаю неправильно в приведенном выше коде?или скажите мне другой способ объявить переменную в файле application.property

1 Ответ

0 голосов
/ 15 мая 2018

Похоже, что Spring пытается здесь сделать, это ввести значение ${crossOrigin} в ваш метод.

  1. В findLocation оно не ломается, потому что нет аргументов метода, в которыхввести значение
  2. В btnSearchClick имеется более одного аргумента, и он не пытается ввести значение
  3. Существует один аргумент, и он пытается ввести значение ${crossOrigin}в AccountMaintenanceSave saveObj

Вы должны просто ввести ${crossOrigin} в @CrossOrigin в верхней части вашего класса?Вот так:

@RestController
@CrossOrigin(origins = "${crossOrigin}")
@RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account")
public class AccountController {

    @Autowired
    AccountService accService;

    ...
}

И доступ к переменной таким образом.Вам нужно будет удалить аннотации @Value из методов вашего контроллера.

Вам также нужно просто указать имя источника в вашем application.properties:

crossOrigin=http://localhost:4200
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...