what is the difference between using or not Spring Beans?

老子叫甜甜 提交于 2019-12-05 13:46:38

Suppose you have 2 DAO classes one for Oracle, the seconde for MySQL, and both classes are implementing a DAO interface. You define an implementation as a bean in Spring configuration file. In the business class you have an attribut of type DAO, while in the spring configuration file you choose the real type wheather Oracle or MySQL to inject or using spring annotation @Autowired

This reduce coupling and it will be easy to move from Oracle to MySQL.

@Service
public class Business {
    @Autowired
    private Dao daoImpl;

    //Business methods that invoks Dao methods 
}

In the Spring configuration file (XML file) you use the following:

<bean id="daoImpl" class="app.com.MySQLDaoImpl OR app.com.OracleDaoImpl"/>

By just changing the class attribut of your bean you change the whole implementation, without any change in your business class !
Good luck.

Your example without Spring doesn't dependency injection! With dependency injection, the actual implementation of the interface is determined outside the code itself in order to reduce the coupling!

You should be able to need another implementation (you could for example switch from one JMS client to another...).

To answer to your last question, using Spring is (a very little bit) less performant but much more flexible.

EDIT : Spring is not the only tool that can be used for DI but it is the most popular and it contains a lot of features. Note that many Java standards also (such as JPA) use DI.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!