Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand SpringFramework and IOC dependency search

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand SpringFramework and IOC dependency search". In daily operation, I believe many people have doubts about how to understand SpringFramework and IOC dependency lookup. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to understand SpringFramework and IOC dependency lookup". Next, please follow the editor to study!

1. Talk about SpringFramework / tell me about your understanding of SpringFramework

SpringFramework is an open source, loosely coupled, layered and configurable one-stop enterprise Java development framework, its core is IOC and AOP, it can more easily build enterprise Java applications, and it can integrate corresponding technologies according to the needs of application development components.

Loosely coupled: in order to describe IOC and AOP, it may be extended that IOC loose coupling related content can be configured: lay the groundwork for the following SpringBoot (convention is greater than configuration) IOC and AOP: Inverse of Control control inversion, Aspect Oriented Programming aspect-oriented programming

two。 Why use SpringFramework

It can be described by the following points:

IOC realizes the decoupling between components.

AOP aspect programming makes the application business unified or specific function enhancement, which can realize the decoupling of application business and enhancement logic.

Bean used in container management applications, managed Bean lifecycle, event and snooping drivers

Web, transaction control, testing, integration with other technologies

3. What modules does SpringFramework contain?

Beans, core, context, expression [core pericardium]

Aop [facet programming]

Jdbc [integrating jdbc]

Orm [integrated ORM framework]

Tx [transaction control]

Web [Web layer technology]

Test [integration testing]

.

4. Comparison between dependency Lookup and dependency injection

5. Comparison between BeanFactory and ApplicationContext

The BeanFactory interface provides an abstract configuration and object management mechanism.

ApplicationContext is a subinterface of BeanFactory, which simplifies integration with AOP, message mechanism, event mechanism, and extensions to the Web environment (WebApplicationContext, etc.)

ApplicationContext mainly extends the following functions:

Support for AOP (AnnotationAwareAspectJAutoProxyCreator acts after initialization of Bean)

Configuration meta-information (BeanDefinition, Environment, comments, etc.)

Resource management (Resource abstraction)

Event-driven mechanisms (ApplicationEvent, ApplicationListener)

Message and internationalization (LocaleResolver)

Environment abstraction (SpringFramework 3.1onwards)

2. History of SpringFramework

Before the Spring technology, J2EE sprang up. At that time, the learning cost of J2EE was extremely high, the development speed was slow, and the performance consumption of the developed program was also high, which could no longer keep up with the needs of the application at that time. In 2002, Rod Johnson wrote a book called "Expert One-on-One J2EE design and development", which questioned the bloated and inefficient problems of the existing J2EE application architecture and EJB framework at that time, and actively looked for and explored solutions.

Based on the idea of ordinary Java class and dependency injection, a simpler solution is proposed, which is the sprout of the core idea of Spring framework.

Two years later, SpringFramework 1.0.0 was born in 2004, and then Rod Johnson wrote a book * * "Expert one-on-one J2EE Development without EJB" * *, which caused a great sensation in the J2EE development world at that time. This book directly told developers that they could not use EJB to develop J2EE applications, but could replace it with a lighter and simpler framework, that is, SpringFramework.

At that time, there were all kinds of doubts in the development world, something like this, Nani? Who is this person who questions the design essence of many bosses of IBM? Why are you so arrogant? Then it was tried by some developers. After using it, it was found that it was really easier to use than EJB, not so bloated, the performance also improved, and some of the features provided were better than EJB, so I slowly switched to SpringFramework.

The update time and main features of major versions of SpringFramework are shown below.

3. IOC dependency lookup

Construction of basic framework

1. Create a Maven module. Take ioc-learning as an example.

two。 Introduce dependency

Org.springframework spring-context 5.2.8.RELEASE

3. Create a profile ioc-learning-dl.xml

4. Declare the normal class Person.java

Public class Person {}

Declaration of 5.ioc-learning-dl.xml configuration file joining Persion

6. Create a startup class

Public class DlApplication {public static void main (String [] args) {/ / read the configuration file using the interface BeanFactory to receive BeanFactory factory = new ClassPathXmlApplicationContext ("dl/ioc-learning-dl.xml"); / / get the object through the id declared in the configuration file Person person = (Person) factory.getBean ("person"); System.out.println (person);}}

7. Run print

Com.huodd.bean.Person@57baeedf

The fully qualified class name + memory address of Person is printed successfully, which proves that the writing is successful.

3.1 byName name Lookup

Step 6 in the above basic framework

Core code

Person person = (Person) factory.getBean ("person")

3.2 byType type lookup

1. Ordinary class

1. Modify the configuration file ioc-learning-dl.xml to remove the id attribute from the declaration of person

two。 Modify startup class

Public static void main (String [] args) {BeanFactory factory = new ClassPathXmlApplicationContext ("dl/ioc-learning-dl.xml"); / / Person person = (Person) factory.getBean ("person"); Person person = factory.getBean (Person.class); System.out.println (person);}

The return value of Class type is directly passed into the parameters of the getBean method, and there is no need to make a strong turn.

3. Run the main method to print as follows

Com.huodd.bean.Person@61862a7f

two。 Interface

1. Create the interface demoDao and the implementation class DemoDaoImpl

Public interface DemoDao {List findAll ();} public class DemoDaoImpl implements DemoDao {@ Override public List findAll () {return Arrays.asList ("user1", "user2", "user3");}}

two。 Modify the declaration of the configuration file ioc-learning-dl.xml to join DemoDaoImpl

3. Modify startup class

Public static void main (String [] args) {BeanFactory factory = new ClassPathXmlApplicationContext ("dl/ioc-learning-dl.xml"); DemoDao demoDao = factory.getBean (DemoDaoImpl.class); System.out.println (demoDao); System.out.println (demoDao.findAll ());}

4. Run the main method to print the result as follows

Com.huodd.dao.DemoDaoImpl@7334aada [user1, user2, user3]

Thus it can be seen that the DemoDaoImpl injection is successful and BeanFactory can find the corresponding implementation class according to the interface type.

3.3 Advanced find

OfType finds multiple based on type

If an interface has more than one implementation class, how to take out all the implementation classes at once? The getBean method used earlier obviously does not meet the need to use the ofType method.

1. Following the above code, the implementation classes for creating two DemoDao are as follows

Public class DemoMysqlDaoImpl implements DemoDao {@ Override public List findAll () {return Arrays.asList ("mysql_user1", "mysql_user2", "mysql_user3");}} public class DemoOracleDaoImpl implements DemoDao {@ Override public List findAll () {return Arrays.asList ("oracle_user1", "oracle_user2", "oracle_user3");}}

two。 Modify the configuration file ioc-learning-dl.xml to add the declaration of the two new implementation classes

3. Modify startup class

Public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("dl/ioc-learning-dl.xml"); Map beans = ctx.getBeansOfType (DemoDao.class); beans.forEach ((beanName, bean)-> {System.out.println (beanName + ":" + bean.toString ());});}

Run the main method to print the result as follows

Com.huodd.dao.impl.DemoMysqlDaoImpl#0: [mysql_user1, mysql_user2, mysql_user3] com.huodd.dao.impl.DemoOracleDaoImpl#0: [oracle_user1, oracle_user2, oracle_user3]

Careful buddies may find out why the return value of the configuration file is read using ApplicationContext instead of BeanFactory.

ApplicationContext is also an interface. Looking at the inheritance chain of the class through IDEA's diagram, you can see that this interface inherits BeanFactory.

There is an explanation in the official article:

The org.springframework.beans and org.springframework.context packages are the basis of SpringFramework's IOC container. The BeanFactory interface provides an advanced configuration mechanism that can manage any type of object. ApplicationContext is a subinterface of BeanFactory. It increases:

Easy integration with SpringFramework's AOP function

Message resource processing (for internationalization)

Event release

Application layer specific context, such as WebApplicationContext used in Web applications

In this way, ApplicationContext includes all the functions of * BeanFactory, and extends more features.

In fact, the main reason for us at present is that there is no getBeansOfType () method in BeanFactory.

WithAnnotation looks up based on annotations

The IOC container can also find the corresponding Bean based on the annotations marked on the class

1. Create an annotation class

@ Documented @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.TYPE) public @ interface animal {}

two。 Create several bean objects

@ Animal public class Dog {} @ Animal public class Cat {} public class Xiaoming {}

Only the Xiaoming class does not add @ Animal annotations

3. Modify the XML configuration file to add the following three declarations

4. Modify startup class

Public class DlApplication {public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("dl/ioc-learning-dl.xml"); Map beans = ctx.getBeansWithAnnotation (Animal.class); beans.forEach ((beanName, bean)-> {System.out.println (beanName + ":" + bean);});}}

5. Run the main method to print the result as follows

Dog: com.huodd.bean.Dog@313ac989 cat: com.huodd.bean.Cat@4562e04d

Delayed search

For some special scenarios, you need to rely on some specific bean in the container, but how do you use the default / or default policy to handle the logic when they don't exist?

Here, let's temporarily delete the declaration of Dog in the xml configuration file.

In this way, when we get the dog, ctx.getBean (Dog.class) will report an error.

NoSuchBeanDefinitionException

1. The existing scenario enables the default policy

Dog dog; try {dog = ctx.getBean (Dog.class);} catch (NoSuchBeanDefinitionException e) {/ / manually create dog = new Dog ();} System.out.println (dog) when Dog cannot be found

Here we write the business code in the catch code block, which is not elegant enough, and the performance needs to be improved, and if each bean is handled in this way later, there will be a huge amount of code.

two。 Check before obtaining under modification

Dog dog = ctx.containsBean ("dog")? (Dog) ctx.getBean ("dog"): new Dog ()

The method containsBean in ApplicationContext is used to check whether there is a specified bean in the container.

There seems to be no problem with this method, but it is important to consider that the parameters passed by this method can only pass the id of bean, not according to the type of bean. If the name of bean is something else, the workload is still huge.

3. Use delayed lookup

The general idea of this mechanism is that when we want to get a Bean, we first return a wrapper class, and wait until we actually use it to "unpack" to check whether there is a Bean object in it.

The method of use is as follows

ObjectProvider dogProvider = ctx.getBeanProvider (Dog.class)

As you can see in the above code, it is handled in accordance with the previous idea, returning a "wrapper" to us, calling the getObject method directly when we use it.

However, if the Bean is not in the container, it will still report NoSuchBeanDefinitionException. Other methods provided by ObjectProvider will be described below.

GetIfAvailable () this method returns null without throwing an exception when Bean is not found

You can use the following methods to implement

Dog dog = dogProvider.getIfAvailable (Dog::new)

IfAvailable () this method is used immediately or intermittently after getting the Bean

The code is as follows

DogProvider.ifAvailable (dog-> System.out.println (dog)); / or use the method reference here, the study on "how to understand SpringFramework and IOC dependency lookup" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report