java - 如何从类获取对象到服务

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

这里我有 AmazonService 类,其中包含 ec2 对象,

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 并在所有其他服务类中使用它。但我在尝试此操作时遇到了上述错误。有人帮我解决这个问题。

最佳答案

更好的是,为什么不利用 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;
    }
}

关于java - 如何从类获取对象到服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803727/

相关文章:

java字符串拆分正则表达式保留定界符

java - 聚合不一致地打印不同的值

jsp - 找不到标签库描述符错误: displaytag & spring

java - JAX-WS 和 Spring 运行时建模器错误

java - 解决 Hibernate 在多线程应用程序中的错误

java - 无法让 springfox-swagger-ui 与 Spring MVC 一起工作

Java 文件读取器找不到合适的文件

java - TSerializer 序列化器 = C# 中的 new TSerializer()

java - Android:放大和缩小页面 curl

java - MessageStore 支持 QueueChannel,带有 Spring Integration+ Java Config