如何从类到服务获取对象

时间:2017-06-28 13:21:03

标签: java spring spring-mvc spring-boot aws-sdk

这里我有一个包含ec2对象的AmazonService类,

import org.springframework.stereotype.Component;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;

@Component
public class AmazonService {

    private AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).build();

    public AmazonEC2 getEc2() {
        return ec2;
    }   
}

我需要从服务类中获取此ec2,如下所示,

@Service
public class SecurityGroupServiceImpl implements SecurityGroupService {



    @Autowired
    AmazonService amazonService;

    final AmazonEC2 ec2 = amazonService.getEc2();

    @Override
    public DeleteSecurityGroupResult deleteSecurityGroup(SecurityGroupDTO securityGroupDTO) {

        DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest()
                .withGroupId(securityGroupDTO.getGroupID());

        DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request);
        System.out.println(response);
        return response;
    }
}

我的Controller类如下,

@Controller
public class SecurityGroupController {

    @Autowired
    SecurityGroupService service;

    @RequestMapping(value = "/deleteSecurityGroup", produces = "application/json", 
            consumes = "application/json", method = RequestMethod.POST)
    private @ResponseBody DeleteSecurityGroupResult deleteSecurityGroup(@RequestBody SecurityGroupDTO securityGroupDTO){

        return service.deleteSecurityGroup(securityGroupDTO);
    }

}

当我试图运行时,我收到错误,

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-28 18:46:21.213 ERROR 7792 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityGroupController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityGroupServiceImpl' defined in file [E:\Project\AWS-SDK-Implimentation\target\classes\com\altimetrik\services\impl\SecurityGroupServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at com.altimetrik.AwsSdkImplimentationApplication.main(AwsSdkImplimentationApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityGroupServiceImpl' defined in file [E:\Project\AWS-SDK-Implimentation\target\classes\com\altimetrik\services\impl\SecurityGroupServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.altimetrik.services.impl.SecurityGroupServiceImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 30 common frames omitted
Caused by: java.lang.NullPointerException: null
    at com.altimetrik.services.impl.SecurityGroupServiceImpl.<init>(SecurityGroupServiceImpl.java:35) ~[classes/:na]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 32 common frames omitted

这里我在各种服务类中使用ec2对象,所以我不想每次在所有服务类中初始化它。相反,我需要在单独的类中创建ec2并在所有其他服务类中使用它。但是我在尝试这个时遇到了上面提到的错误。有人帮我解决了这个问题。

3 个答案:

答案 0 :(得分:2)

更好的是,为什么不利用Java配置(非常适合从第三方实例化bean),只需将AmazonEC2作为实际的Spring bean。

@Configuration
public class AmazonServiceConfiguration {
  @Bean
  public AmazonEC2 ec2() {
    return AmazonEC2ClientBuilder.standard()
      .withRegion(Regions.AP_SOUTH_1).build();
  }   
}

您的服务实施:

@Service
public class SecurityGroupServiceImpl implements SecurityGroupService {    
    @Autowired    
    AmazonEC2 ec2;

    @Override
    public DeleteSecurityGroupResult deleteSecurityGroup(SecurityGroupDTO securityGroupDTO) {

        DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest()
                .withGroupId(securityGroupDTO.getGroupID());

        DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request);
        System.out.println(response);
        return response;
    }
}

答案 1 :(得分:1)

当您尝试从ec2类设置SecurityGroupServiceImpl时,AmazonService类实际上并未创建SecurityGroupServiceImpl类。因此,请在加载AmazonService

后尝试在MaxProcs: 8 Source : 2.0001ms Quick sort : 3.0002ms Merge sort : 8.0004ms Insertion sort : 929.0532ms Goroutine num: 1 Source : 2.0001ms Goroutine num: 4 Insertion sort : 927.0531ms Quick sort : 930.0532ms Merge sort : 934.0535ms 中获取ec2

答案 2 :(得分:0)

创建SecurityGroupServiceImpl时,没有amazonService。它是后来自动装配的,所以试图获得某些东西会产生NPE。

而是在@PostConstruct

中移动init
@PostConstruct
public void init() throws Exception {
    ec2 = amazonService.getEc2();
}

当然,这个领域不应该是最终的。

或者从字段中删除@Autowire并移至构造函数并从构造函数初始化最终字段(在此处{@ 3}}上阅读@Autowired on Constructors部分)