In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "how to achieve a budding version of Spring container", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve a budding version of Spring container" this article.
Start with what is IOC?
Spring-- Spring, the spring of the Java programming world is brought by a musician-Rod Johnson.
Rod Johnson has written two great books, Expert One-on-One J2EE Design and Development and Expert One-on-One J2EE Development without EJB, which have raised the banner of challenging the orthodox Java EE framework EJB.
Rod Johnson is not only a flag bearer, but also developed the lightweight framework of Spring, like a brave dragoon, launched a charge against EJB, and finally defeated EJB, making Spring the de facto standard of Java EE.
The two major kernels of Spring are IOC and AOP, of which the most core is IOC.
The so-called IOC (inversion of Control): the container is responsible for controlling the life cycle of objects and the relationship between objects. In the past, we created what we wanted, but now the container sends us what we need.
In other words, it is no longer the object that references it, but the container that controls the life cycle of the object. For a specific object, it used to control other objects, but now all objects are controlled by the container, so this is called control inversion.
You may also hear another concept, DI (dependency injection), which means that the container injects its dependent classes into it when it instantiates an object, and we can also think of DI as a complement and implementation of IOC.
Factories and Spring containers
Spring is a mature framework, in order to meet the scalability and achieve a variety of functions, so its implementation is like a staggered tree, now let's look away from the Spring itself and see how a budding Spring container can be implemented.
The IOC of Spring is essentially a big factory. Let's think about how a factory works.
Produce products: the core function of a factory is to produce products. In Spring, instead of instantiating Bean itself, you hand it over to Spring. How should it be implemented? There is no doubt about the answer, reflection.
So how is the production management done in this factory? You should also know-- the factory model.
Inventory products: factories generally have warehouses, which are used to stock products. After all, the products produced cannot be pulled away immediately. Spring we all know that it is a container, and what is stored in this container is the object. You can't always reflect the created object on the spot every time you come to pick up the object. You have to save the created object.
Order processing: and most importantly, what is the basis for the factory to provide products? Order. These orders may be varied, signed on the cable, signed by the factory, and signed by the factory sales door-to-door. Finally, after processing, guide the shipment of the factory.
There are also such orders in Spring, which are our definition and dependencies of bean, either in the form of xml or the most familiar form of annotations.
What does our budding Spring container look like?
Orders: Bean definition
Bean can be defined through a configuration file, which we will parse into a type.
Beans.properties
In order to be lazy, the most convenient parsing properties is directly used here, using a type of configuration to represent the definition of Bean, where key is beanName,value and class.
UserDao:cn.fighter3.bean.UserDao
BeanDefinition.java
Bean defines the class, and bean defines the corresponding entity in the configuration file
Public class BeanDefinition {private String beanName; private Class beanClass; / / omit getter, setter} get order: resource loading
After taking the order, it is necessary for the sales to hand over to the production department to let the production department know the specification and quantity of the goods.
The resource loader, which is here to do this, loads the configuration in the configuration file.
Public class ResourceLoader {public static Map getResource () {Map beanDefinitionMap = new HashMap (16); Properties properties = new Properties (); try {InputStream inputStream = ResourceLoader.class.getResourceAsStream ("/ beans.properties"); properties.load (inputStream); Iterator it = properties.stringPropertyNames (). Iterator () While (it.hasNext ()) {String key = it.next (); String className = properties.getProperty (key); BeanDefinition beanDefinition = new BeanDefinition (); beanDefinition.setBeanName (key); Class clazz = Class.forName (className); beanDefinition.setBeanClass (clazz); beanDefinitionMap.put (key, beanDefinition) } inputStream.close ();} catch (IOException | ClassNotFoundException e) {e.printStackTrace ();} return beanDefinitionMap;}} order assignment: Bean registration
Object registry, here for singleton bean cache, we greatly simplify, default all bean is singleton. You can see that the so-called singleton registration is also very simple, but to store objects in HashMap.
Public class BeanRegister {/ / Singleton Bean cache private Map singletonMap = new HashMap (32); / * get singleton Bean * * @ param beanName bean name * @ return * / public Object getSingletonBean (String beanName) {return singletonMap.get (beanName) } / * register singleton bean * * @ param beanName * @ param bean * / public void registerSingletonBean (String beanName, Object bean) {if (singletonMap.containsKey (beanName)) {return;} singletonMap.put (beanName, bean);}} production workshop: object factory
All right, it's time for our most critical production department. In the factory, it is the workshop that produces the product, and in the IOC container, the production object is BeanFactory.
Object factory, one of our core classes, creates a bean registry when it is initialized, and finishes loading resources.
When you get a bean, first fetch it from the singleton cache. If you don't get it, create and register a bean.
Public class BeanFactory {private Map beanDefinitionMap = new HashMap (); private BeanRegister beanRegister; public BeanFactory () {/ / create bean registry beanRegister = new BeanRegister (); / / load resource this.beanDefinitionMap = new ResourceLoader () .getResource () } / * get bean * * @ param beanName bean name * @ return * / public Object getBean (String beanName) {/ / fetch Object bean = beanRegister.getSingletonBean (beanName) from the bean cache; if (bean! = null) {return bean } / / create bean return createBean (beanDefinitionMap.get (beanName)) according to bean definition;} / * * create Bean * * @ param beanDefinition bean definition * @ return * / private Object createBean (BeanDefinition beanDefinition) {try {Object bean = beanDefinition.getBeanClass (). NewInstance () / / cache bean beanRegister.registerSingletonBean (beanDefinition.getBeanName (), bean); return bean;} catch (InstantiationException | IllegalAccessException e) {e.printStackTrace ();} return null;}} production sales: test
UserDao.java
Our Bean class is very simple
Public class UserDao {public void queryUserInfo () {System.out.println ("A good man.");}}
Unit testing
Public class ApiTest {@ Test public void test_BeanFactory () {/ / 1. Create a bean factory (while loading resources and creating a singleton bean registry) BeanFactory beanFactory = new BeanFactory (); / / 2. Get bean for the first time (create bean through reflection, cache bean) UserDao userDao1 = (UserDao) beanFactory.getBean ("userDao"); userDao1.queryUserInfo (); / / 3. Get bean for the second time (get bean from cache) UserDao userDao2 = (UserDao) beanFactory.getBean ("userDao"); userDao2.queryUserInfo ();}}
Running result
A good man.
A good man.
At this point, we have a fledgling version of the Spring container.
The above is all the content of the article "how to implement a budding version of Spring Container". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.