代码之家  ›  专栏  ›  技术社区  ›  Ayoub k

我不应该在Spring引导项目中使用“new”关键字吗?

  •  0
  • Ayoub k  · 技术社区  · 6 年前

    我正在研究Spring Boot Rest API,最终我使用了 new 关键字。

    我在想,当我在程序中使用新的关键字时,我做了什么错事吗?如果绝对禁止在实际项目中使用新关键字。

    如果答案是肯定的,我应该为我写的每门课做注释吗? @component 注释,以便我可以使用 @autowired .

    如果答案是否定的,我们什么时候才能打破这个规则?

    5 回复  |  直到 6 年前
        1
  •  1
  •   Saikat    6 年前

    可以在Spring应用程序中使用new关键字创建对象。

    但是这些对象将不在Spring应用程序上下文的范围内,因此不是Spring管理的。

    由于这些不是Spring管理的,所以任何嵌套的依赖级别(例如,您的服务类具有对存储库类的引用等) 无法解决。

    因此,如果您尝试在服务类中调用一个方法,那么最终可能会得到存储库的空指针。

    @Service
    public class GreetingService {
        @Autowired
        private GreetingRepository greetingRepository;
        public String greet(String userid) {
           return greetingRepository.greet(userid); 
        }
    }
    
    @RestController
    public class GreetingController {
        @Autowired
        private GreetingService greetingService;
        @RequestMapping("/greeting")
        public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
            return String.format("Hello %s", greetingService.greet(name));
        }
        @RequestMapping("/greeting2")
        public String greeting2(@RequestParam(value = "name", defaultValue = "World") String name) {
          GreetingService newGreetingService = new GreetingService();
          return String.format("Hello %s", newGreetingService.greet(name));
        }
    }
    

    在上面的例子中 /greeting 会工作但 /greeting2 将失败,因为未解析嵌套的依赖项。

    因此,如果您希望对象是Spring管理的,那么您必须自动连接它们。 一般来说,对于视图层POJO和自定义bean配置,您将使用 new 关键字。

        2
  •  2
  •   Amit Phaltankar    6 年前

    没有使用或不使用的规则 new

    如果你想让你的对象由Spring管理,或者你想自己处理,那就取决于你了。

    Spring简化了对象创建、依赖关系管理和自动连接,但是如果您希望类中没有对象,可以使用 新的

        3
  •  1
  •   Ori Marko    6 年前

    你会 需要 new 在春季模拟测试中,当您必须创建一个对象作为服务,并将模拟对象作为DAO注入时。

        4
  •  1
  •   MohammadReza Alagheband    6 年前

    看看下面的代码;如您所见,根据一个条件,有必要根据需要动态加载广告。所以在这里您不能@autowire这组项目,因为所有的信息都是从数据库或外部系统加载的,所以您只需要相应地填充您的模型。

    if (customer.getType() == CustomerType.INTERNET) {
        List < Advertisement > adList = new ArrayList < Advertisement > ();
        for (Product product: internetProductList) {
            Advertisement advertisement = new Advertisement();
            advertisement.setProduct(product);
            adList.add(advertisement);
        }
    }
    

    注意,使用弹簧 管理外部依赖项 例如,将JDBC连接插入DAO或配置 指定要使用的数据库类型。

        5
  •  1
  •   Munish Chandel    6 年前

    我想可以用 new 关键字,但您应该了解不同原型(控制器、服务、存储库)之间的区别。

    您可以按照此问题进行操作,以获得一些清晰的信息:

    What's the difference between @Component, @Repository & @Service annotations in Spring?

    使用适当的注释将允许您正确地使用DI(依赖注入),这将有助于为SpringBoot应用程序编写切片测试。也 Service , Controller Repository 组件创建为 Singleton ,所以更少的GC开销。此外,还可以使用 新的 关键字不是由Spring管理的,默认情况下,Spring不会在使用new创建的对象中插入依赖项。

    春季官方文件: https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html