为什么使用Springbeans而不是对象初始化
我试图理解春豆的概念,以及为什么我应该使用它们。如果我创建一个bean并使用它打印出这样的内容为什么使用Springbeans而不是对象初始化,spring,Spring,我试图理解春豆的概念,以及为什么我应该使用它们。如果我创建一个bean并使用它打印出这样的内容 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); Account acc = (Account)context.getBean("account"); acc.printAccName(); 为什么不创建这样一个类的对象呢 Account acc2 = new Account(); acc.p
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Account acc = (Account)context.getBean("account");
acc.printAccName();
为什么不创建这样一个类的对象呢
Account acc2 = new Account();
acc.printAccName();
我一直在看一些视频并阅读了一些内容,但我没有得到为什么它更好的答案。通常,您注入的是业务逻辑或服务,这通常是系统中的变化 您正在尝试注入一个域对象
帐户
这些对象不受更改影响,因此可以通过新建来创建对象。也许,这就是让你困惑的地方
其想法是让容器处理定期更改的逻辑或服务的实例化,这样您就可以轻松地交换它们,而无需打开客户机类,因为这些类可能已经在生产中,经过测试,开发人员可能会引入新的bug并破坏它们。避免这种情况的一种方法是遵循一个称为的原则。然后编写抽象代码,以便通过依赖项注入轻松地注入具体实现
想象一下下面的情景。对于书店,对于如何将书籍保存到数据库中,您有不同的实现,例如使用JDBCBookServiceJDBCImpl
,或使用ORMBookServiceHibernateImpl
等
// 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"/>
通过让容器处理这个问题,您可以注入不同的实现,而不必接触客户机类,甚至不必知道将传递哪个实现
检查此项,它解释了使用Spring实现此功能的方法
请记住,在Spring中,您可以使用java注释或xml,并且有不同的方法来注入依赖项,例如通过get/set、构造函数等。这只是一般DI概念的一个示例。设计取决于开发人员。使用bean的另一个原因是帮助测试 我们还将RestTemplate提取到@Bean中,以便于 测试(这样可以更容易地模拟)
除了Spring,你应该了解什么是控制反转(),熟悉坚实的原理感谢我将阅读的资源。谢谢你的回答,我不确定的一件事是。通过让容器处理这个问题,您可以在不接触类的情况下注入不同的实现,这不正是多态性吗?没错!您可以在接口或抽象类中定义方法。然后使用该接口或抽象类作为类型,并注入该接口的实现,该接口应该实现该方法