为什么使用spring bean而不是对象初始化

时间:2018-04-02 21:45:39

标签: spring

我试图理解春豆的想法以及我为什么要使用它们。如果我创建一个bean并使用它来打印这样的东西。

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Account acc = (Account)context.getBean("account");
acc.printAccName();

为什么不像这样创建该类的对象

Account acc2 = new Account();
acc.printAccName();

我一直在看一些视频并做了一些阅读,但我没有得到答案为什么它更好。

2 个答案:

答案 0 :(得分:1)

通常,您注入的是业务逻辑或服务,这通常是系统中的变化。

您正在尝试注入域对象Account这些对象不会发生变化,因此可以通过new创建对象。也许,这就是令你困惑的事情。

这个想法是让容器处理定期更改的逻辑或服务的实例化,以便您可以轻松地交换它们而无需打开客户端类,因为这些可能已经在生产,测试过,开发人员可能引入新的错误和破坏事物。避免这种情况的一种方法是遵循一个名为Open-Closed principle的原则。然后编写抽象代码,以便通过依赖注入轻松注入具体实现。

想象一下以下的情景。对于书店,您可以使用不同的方法将书籍保存到数据库中,例如使用JDBC BookServiceJDBCImpl,或使用ORM BookServiceHibernateImpl等。

    // Create & get the Spring container, where you configure your implementations
    // e.g. bookServiceJDBC, or bookServiceHibernate
    ApplicationContext container = new ClassPathXmlApplicationContext("spring-config.xml");

    // the container loads the appropriate bean say bookServiceHibernate
    BookService bookService = (BookService) container.getBean("bookService");

    //Create a new book this is a domain object usually you use new
    Book newBook = new Book("1234", "Spring in Action","Rod Johnson");
    //Now save the book using the implementation defined in the 
    //container 
    bookService.registerNewBook(newBook);

这是容器文件的一部分可能的样子,在这里你定义了具体的实现:

<bean id="bookService" class="service.BookServiceHibernateImpl"/>

通过让容器处理这个,您可以注入不同的实现,而无需触及客户端类,甚至不知道将传递哪个实现。

检查这个Dependency Injection blog post它解释了使用Spring实现它的方法。

请记住,在Spring中你可以使用java注释或xml,并且有不同的方法来注入依赖关系,例如通过get / set,constructors等,这只是一般DI概念的一个说明性例子。设计取决于开发人员。

答案 1 :(得分:0)

使用bean的另一个原因是为了帮助测试。

  

我们还将RestTemplate提取到@Bean中以使其更容易   测试(可以通过这种方式更容易嘲笑)。 Link

相关问题