Introduction to IOC

xiaoxiao2021-04-05  259

Introduction to IOC

This article is intended to introduce the concept of Inversion Of Control and how it simplifies and more efficiently performs applications. We will view different types of IOC frameworks. By displaying IOCs, you will also be able to see why IOC has attracted so many interests. IOC Theory Description IOC is what is the best way that it can provide is to see some simple examples. The following JDBCDataManager class is an access to the application for the database. This application uses the raw JDBC's most lasting layer. In order to access the persistence layer through the JDBC, JDBCDataManager requires a DataSource object. The standard way is hard-coded DataSource object to the class, like this: code: ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------- Public Class JDBCDATAMANAGER { Public void accessData () {DataSource DataSource = New DataSource (); // access data ...}} JDBCDataManager is dealing with all data access in our application, hard-coded DataSource is not bad, but we may want to be more abstract DataSource, perhaps Get it through some system attribute object: code: --------------------------------------- ----------------------------------------- Public Class JDBCDataManager {public void accessData () {Datasource DataSource = ApplicationResources.getDataSource ();}} In any case, JDBCDataManager has to get DataSource. IOC has taken different ways - using IOC, JDBCDataManager will declare it for a DataSource, the IOC framework will provide one. This means that the components will no longer need to know how to get relying, and bring more simple, more focused, and more flexible code. The idea behind the IOC framework IOC is not very new; in fact, IOC is just a new abbreviation to the injection of the original Dependency Inversion PrinciPle. For IOC interest is its new thing, there is a large number of frameworks to start actual development to assist IOC. The IOC framework is also an IOC mode catalyst - the work of the frame is a binder formed in the IOC system. When IOC's universal principles are generally accepted, there are several different implementations in numerous frameworks. The developers of PicoContainer initially define three types of IOCs, which is to distinguish other frameworks for other frameworks. First of all, these types are simply called Type1, 2 and 3, but in the Martin Fowler article, Inversion of Control Containers and the Dependency Injection Pattern he specifies more meaningful terms for these three types, which we will use below. . In the remainder of the article, we briefly view Avalon, then discuss two popular IOC frameworks, Spring and PicoContainer, they all offer IOC types. Injection Interface (Type 1) Interface Injection Using the IOC injection interface, the component needs to implement the special interface provided by the container for configured.

Let's take a look at the reconstruction of JDBCDataManager: Code: ------------------------------------------------------------------------------------------------------------------------- --------------------------------------------- Import org.apache. avalon.framework *;. public class JDBCDataManger implements Serviceable {DataSource dataSource; public void service (ServiceManager sm) throws ServiceException {dataSource = (DataSource) sm.lookup ( "dataSource");} public void getData () {// use dataSource This form of IOC has been widely used, which is longer than IOC this term. Most readers may have used this form of IOC, for example, when using an EJB framework. Your component extends and implements a specific interface, which is called itself by the framework. Avalon Framework has been provided for many years for many years, and is not popular like Spring and PicoContainer, it is likely to be due to the drawbacks of this implementation. The condition for achieving a special interface is to make the code feel bloated, and it also allows your application to couple with the framework. The following two IOCs provide a benefit far exceed this IOC form. Setter Injection (Type 2) Use IoC's setter injection, some external metadata is used to resolve dependence issues. In Spring, this metadata takes the form of an XML configuration file. Using this form of IOC, JDBCDataManager class looks like a normal bean: code: -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------ Public Class JDBCDataManger {private dataSource dataSource; public void setDataManager (dataSource dataSource) {this.dataSource = dataSource;} public void getData () {// use dataSource for something}} we JDBCDataManager component exposes its dataSource attribute set to allow it Spring . Spring is done by XML configuration.

So, we first define a data source bean (can be reused by multiple components) code: -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- jdbc: mydb: // server: port / mydb root Next, we define an instance of a manager (Data Manager) and pass the data source to it: code: ----------------------- -------------------------------------------------- ------- at runtime The JDBCDataManager class will be instantiated using the correct DataSource dependency reference, and then we will be able to access the bean through the Spring framework itself. This definition of this dependency makes a simple unit test: for the hypothetical object, simply define an XML file, instead of the normal XML file, and then test it. Perhaps the biggest advantage of SETTER injection is that the application code does not need to be bind to the container in any way, but this also has drawbacks? Can't clearly know the relationship between JDBCDataManager components and other relationships. It seems that DataSource is magically passed to JDBCDataManager, as depends on the manager to complete these things outside of Java code. An additional disadvantage is that Spring requires Getters and setters to rely on its dependency. You must expose you may not want to expose, potentially destroy the data package principles, at least, make the interface of the class more complex than what you need. Spring metadata is described in XML, can't verify them in the compile period of the normal Java compilation phase, meaning that the critical dependency can only be seen during the runtime. Construct Function Injection Constructor Injection (Type 3) Constructor Injection is basically based on the principle of "good citizen" good citizen. Good citizen mode is proposed by Joshua Bloch to describe the object is completely set up and perform the verification required when creating. In practice, this means that after instantiation, the object does not need to invoke more methods to ensure their availability. That is, you can make sure you can use it after you have created an object.

This simplifies your code and reduces the code written by the defensive check, and your code is more defensive in the whole. Such code is also easier to test. Using the constructor, you have to register an object into the framework, use the specified parameters (can be created in turn by the frame) and request an instance at this time. The registered components must implement a constructor, which can be used to be used for injection. Recently, Spring has begun to support this IOC form, but we look at PicoContainer, which is the framework that is built on this principle. Look at JDBCDataManager, now use the constructor injection frame to re-encode it. Code: ------------------------------------------------ -------------------------------- Public Class JDBCDATAMANGER {Private Datasource DataSource; Public JDBCDataManger (Datasource Datasource) {this.DataSource = DataSource;} public void getData () {// use datasource for something}} is not using a configuration file, PicoContainer is using some old Simply New Yava code to bring everything together: // Create a DataSource Bean code: ----------------------------------------------- -------------------------------- BasicDataSource DataSource = New BasicDataSource (); DataSource.SetDriverClassName ("com.mydb. JDBC.Driver "); DataSource.SetURL (" JDBC: MySQL: // LocalHost: 3306 / MYDB "); DataSource.setUserName (" Bob "); // Create a container MutablePicocontainer Pico = New DefaultPicoContainer (); // Register Components with containerConstantParameter dataSourceParam = new ConstantParameter (dataSource); String key = "DataManager"; Parameter [] params = {dataSourceParam}; / ** Now each request for a DataManager will instantiate * a JDBCDataManager object with our defined * dataSource object * / pico .reg ISTERComponentImplement (Key, JDBCDataManager.class, PAREMS);

In order to obtain an example of the JDBCDataManager object, we have to reference this class through its key: [code] JDBCDataManager DM = (JDBCDataManager) Pico.getComponentInstance (key); IoC, ioc, our application code (except Pico specific) like Setter Outside of the configuration), it is independent of the frame itself, and bringing you the advantage of using the "good citizen" mode. In addition, PicoContainer only requires a constructor, we only need to do very little preparation to use the IOC framework to inject IOC relative to Setter. The potential problem of this way is that when inheriting, it will become more complicated when using inheritance, and he will cause some things when you use a constructor to complete some other things, not a simple instantiation of objects. IOC Practice: The Data Access Object Pattern is currently, our JDBCDataManger class uses SQL to get our data. If we want to access data or jdo by hibernate? We can use a new class to replace the use of JDBCDataManager, but a better solution is to use the Data Access Object (DAO) mode. SUMMARY, DAO mode defines a method such that ordinary value objects can be used to set up and acquire data (considering ordinary javabeans) and is done by an abstract data access object. Our existing JDBCDataManager will remain unchanged. We will add DataManager interface, which will implement our data access. For the consideration of the debate, we also added Hibernate implementation, HibernatedataManager. JDBCDataManager and HibernatedataManager have started data access objects. Suppose we have used IOC, changing to use DAO is very simple. Assume that we use the Spring code above, we can use Hibernate instead of the JDBC configuration by the HibernatedAtamanager by the HibernatedataManager instead of the JDBCDataManager class. When switching the DAO implementation, our application code will remain unchanged, assuming that they are looking forward to the DataManager interface instead of a JDBCDataManager implementation. By using two implementations, we are merged with the DAO mode with abstract factory mode Abstract Factory Pattern. In the effect, the IOC framework undertakes the role of the factory itself. During the development process, use such a model makes it easy to move to another persistent mechanism, and it makes a small settings in your development environment to make settings in the publishing environment, greatly. The two implementations of DataManager can be the same code base, which switching them is negligible. Spring contrast PicoContainer PicoContainer and Spring are finely different from setting your IOC bindings. Spring can be configured to do not require an XML configuration file or pass Java directly, but PicoContainer requires a Java binding (even if the PicoExtras project provides XML configuration support). I quickly concluded that the XML profile started to use (as someone recently pointed out, all of these different profiles almost began to become a new language of their own), although it is better to be a personal appetite.

If you need multiple configurations (for example, a development, another for the release), a XML-based system can be better, this is just a configuration management. Both are light frames? They can work well with other frameworks and have an additional advantage that they have coupling them. PicoContainer is a smaller in both; it starts to work with the external product like Hibernate without providing the IOC framework. It is worth noting that Spring is not just an IOC framework: it also provides a web application and AOP framework, and there are some universal support classes, which have increased the size of Kud. Personal opinion, I found that Spring's web application framework is very flexible. However, it looks more than the Struts framework in configuration, and there is no rich support class. In addition, AOP features are still developing, but you may not expect it to become a pure AOP frame, such as AspectWerkz or AspectJ. If you plan to use the class provided by Spring, you will find it a good choice. If, of course, you are happy to implement these (or relying on external projects to provide them) At this time, Pico's small-on-how maybe a decision. Both support constructors IOC injection, but only Spring supports SETTER injection? If you prefer setter injection, Spring is first. Conclusion I hope that I have already demonstrated the use of IOC in your application, you can get neat and more flexible code. Spring and PicoContainer can be simply introduced to existing projects as part of the reconstructed work, and their introduction promotes future reconstruction work. Those items that take the IOC from the beginning will find that their application code will be more easier to define the relationship between internal components, and will be more flexible: http://www.javaresearch.org/article/showArticle.jsp? Column = 23 & three = 40952 & forbidden = 8

转载请注明原文地址:https://www.9cbs.com/read-132049.html

New Post(0)