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

What are the features of Spring IOC

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

Share

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

This article focuses on "what are the features of Spring IOC". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the features of Spring IOC"?

I. Preface

Multithreading, locks, JVM tuning, all memorized flowers, how to write code or messy?

Why is it that these important knowledge from books, classes, and interviews do not improve your coding ability in actual programming?

First of all, these knowledge in the actual Internet business development, is almost not commonly used, almost lock and multi-threaded scenarios, in order to improve performance is also basically the use of distributed design and implementation. Most of these seemingly technical knowledge are packaged in components with non-business logic functions, while programmers pay little attention to business development. So it's almost impossible to improve your code if you know this, most of which is that you have a hand in checking complex bug.

Just like knowing Chinese characters, can you write poems and songs? Can you draw mountains and rivers if you know RGB? Can you dance in a swaying posture when you can jump? That's impossible, don't think about your ass around Gabu and say you know martial arts!

If you really want to write the code well, you need to accumulate data structures and algorithmic logic little by little (not just mechanically brush through a few questions. You do not understand why, no matter how much is futile), the next thing to do is to understand the design pattern and architecture design, and finally to constantly apply and summarize. In this process you will come into contact with business, products, operations, coding is only the final concrete implementation, not the most important part of the whole process, more important than coding is logical design.

Second, interview questions

Thank you for the plane. , this holiday to eat barbecue again by Spring, hey hey, test results interview!

Interviewer: how are you going today, plane? have you learned everything I asked you last time?

Xie Jing: @ Resource is a note provided by JDK javax.annotation.Resource. Ha, I also learned about the injection of Bean.

Interviewer: it's good to remember some. When you were doing Bean injection, did you notice the features of Spring IOC? what did you use?

Xie Jing: well, it uses the configuration of Bean, BeanDefinitionRegistryPostProcessor's definition of Bean, and FactoryBean.

Interviewer: OK, I'll talk to you today, alias, autowire, depends-on, factory-method, lookup-method and so on. Let's see how they are applied in practice.

III. SpringIOC characteristics

IOC (Inversion of Control), the core idea of inversion of control is that the use of resources is not managed by their own users, but by third parties who do not use resources. This advantage is that the resources are centrally managed, configurable and easy to maintain, while reducing the dependence of both sides to achieve low coupling.

As early as 1988, Ralph E. Johnson & Brian Foote wrote the paper "Designing Reusable Classes"

One important characteristic of a framework is that the methods defined by the user to tailor the framework will often be called from within the framework itself, rather than from the user's application code. The framework often plays the role of the main program in coordinating and sequencing application activity. This inversion of control gives frameworks the power to serve as extensible skeletons. The methods supplied by the user tailor the generic algorithms defined in the framework for a particular application.

Next, I will introduce some of the core features of IOC, because these are not only interview sites, but also functional classes that need to be used in the development of middleware or widgets, which are summarized as follows:

1. Xml configuration 1.1 alias

Test class

Public class UserService {

Private UserDao userDao

Public UserService () {

System.out.println ("I'm initialized, UserService")

}

/ /... get/set

}

Xml configuration

Unit testing

@ Test

Public void test_alias () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-alias.xml")

Logger.info ("get Bean: {}", beanFactory.getBean ("userService"))

Logger.info ("get Bean via alias: {}", beanFactory.getBean ("userService-alias01"))

Logger.info ("get aliases for Bean via aliases: {}", beanFactory.getBean ("userService-alias02"))

}

Test result

23Rom 01VO1RV 29.872 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserService@2a40cd94

23Rom 01 Returning cached instance of singleton bean userService' 29.872 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Returning cached instance of singleton bean'

23 Bean 01Rank 29.872 [main] INFO org.itstack.interview.test.ApiTest-get Bean via alias: org.itstack.interview.UserService@2a40cd94

23Rom 01 Returning cached instance of singleton bean userService' 29.872 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Returning cached instance of singleton bean'

23Bean 01org.itstack.interview.UserService@2a40cd94 29.872 [main] INFO org.itstack.interview.test.ApiTest-get aliases for Bean through aliases: org.itstack.interview.UserService@2a40cd94 purpose: for aliases for Bean use: in the xml configuration we can give an alias to a Bean and a new alias. 1.2 autowire

Test class

Public class UserDao {

Public UserDao () {

System.out.println ("I'm initialized, UserDao")

}

}

Xml configuration

Unit testing

@ Test

Public void test_autowire () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-autowire.xml")

Logger.info ("get Bean by manual configuration dependency: {}", beanFactory.getBean ("userService-by-property"))

Logger.info ("get Bean by autoconfiguration dependency: {}", beanFactory.getBean ("userService-by-autowire"))

}

Test result

23 Bean by 05VR 55.501 [main] INFO org.itstack.interview.test.ApiTest-get Bean by manual configuration dependency: org.itstack.interview.UserService@679b62af

23Rom 05RV 55.501 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Returning cached instance of singleton bean 'userService-by-autowire'

23 Bean by 05VR 55.501 [main] INFO org.itstack.interview.test.ApiTest-get Bean by autoconfiguration dependency: org.itstack.interview.UserService@5cdd8682

Purpose: autowire is used to inject attributes in the class to Spring management: in xml configuration, there are two ways: manual configuration dependency, automatic configuration dependency, manual is basically very common, automatic configuration may be more for the use of annotations. In fact, the autowire here and annotations have the same role, autowire several options, byName, byType, constructor and so on. 1.3 factory-method

Test class

Public class StaticFactoryBean {

Static public UserDao getUserDaoByStatic () {

Return new UserDao ()

}

}

Xml configuration

Unit testing

@ Test

Public void test_factory_method () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-factory-method.xml")

Logger.info ("get Bean: {}", beanFactory.getBean ("staticFactory-method"))

}

Test result

23RV 15RV 28.950 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@588df31b

23RV 15RV 28.950 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Returning cached instance of singleton bean' staticFactory-bean'

Purpose: use of factory methods that identify static factories (factory methods are static): the core is to add factory-method= "getUserDaoByStatic" to the xml configuration so that the instantiated content of the corresponding static method can be called at initialization time. 1.4 factory-bean

Test class

Public class StaticFactoryBean {

Public UserDao getUserDao () {

Return new UserDao ()

}

}

Xml configuration

Unit testing

@ Test

Public void test_factory_bean_method () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-factory-method.xml")

Logger.info ("get Bean: {}", beanFactory.getBean ("staticFactory-bean"))

}

Test result

23RV 15RV 28.950 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@33b37288

Purpose: factory-bean, instance factory class: factory-bean and factory-method need to be used together. Factory-method= "getUserDao" calls the corresponding fee static method to return the instantiation result. 1.5 depends-on

Xml configuration

Unit testing

@ Test

Public void test_depends_on () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-depends-on.xml")

Logger.info ("get Bean: {}", beanFactory.getBean (UserService.class, "userService") .getUserDao ())

}

Test result

I'm initialized, UserDao.

I'm initialized, UserService.

23RV 24RV 14.678 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@45afc369

Purpose: to deal with dependency initialization order use: if you do not use depends-on= "userDao", then the first initialization according to the Spring configuration is UserService, which you need to use when you need to deal with initialization dependencies. 1.6 lookup-method & ApplicationContextAware

Test class

Public class UserDaoProvider implements ApplicationContextAware {

Private ApplicationContext applicationContext

Public UserDao getUserDao () {

Return applicationContext.getBean ("userDao", UserDao.class)

}

@ Override

Public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {

This.applicationContext = applicationContext

}

}

Xml configuration

Unit testing

@ Test

Public void test_lookup_method () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-lookup-method.xml")

Logger.info ("get Bean: {}", beanFactory.getBean (UserDaoProvider.class, "provider") .getUserDao ())

Logger.info ("get Bean: {}", beanFactory.getBean (UserDaoProvider.class, "provider") .getUserDao ())

}

Test result

I'm initialized, UserDao.

16RV 29RH 25.813 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Finished creating instance of bean 'userDao'

16RV 29RV 25.813 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@1188e820

16RV 29RH 25.813 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Creating instance of bean 'userDao'

I'm initialized, UserDao.

16RV 29RH 25.814 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Finished creating instance of bean 'userDao'

16RV 29RV 25.814 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@2f490758

Objective: to obtain the prototype pattern under the singleton case, and a new object must be generated each time. Use: in fact, the core lies in the use of ApplicationContextAware and scope= "prototype" configuration, Spring internal implementation for the use of Cglib methods, re-generation of subclasses, rewrite configuration methods and return objects to achieve the effect of dynamic change. two。 Interface class 2.1 FactoryBean

Test class

Public class MyFactoryBean implements FactoryBean {

@ Override

Public UserDao getObject () throws Exception {

Return new UserDao ()

}

@ Override

Public Class getObjectType () {

Return UserDao.class

}

@ Override

Public boolean isSingleton () {

Return true

}

}

Xml configuration

Unit testing

@ Test

Public void test_factory_bean () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-factory-bean.xml")

Logger.info ("get Bean: {}", beanFactory.getBean ("userDao"))

}

Test result

2336RV 19.339 [main] INFO org.itstack.interview.test.ApiTest-get Bean:org.itstack.interview.UserDao@3bd94634

Purpose: the Bean used to generate Bean, called FactoryBean use: in fact, this use has been mentioned in the previous chapter on how to inject Bean into Spring, and has been used in some ORM frameworks, RPC-Starter, and so on. 2.2 BeanPostProcessor

Test class

Public class MyBeanPostProcessor implements BeanPostProcessor {

@ Override

Public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {

System.out.println ("before initialization:" + beanName)

Return bean

}

@ Override

Public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {

System.out.println ("after initialization:" + beanName)

Return bean

}

}

Xml configuration

Unit testing

@ Test

Public void test_bean_post_processor () {

BeanFactory beanFactory = new ClassPathXmlApplicationContext ("spring-config-bean-post-processor.xml")

}

Test result

Before initialization: userDao

After initialization: userDao

1614 38 Finished creating instance of bean 32. 686 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory-Finished creating instance of bean 'userDao'

Objective: to get the actions before and after initialization of the Bean object and do the corresponding processing: BeanPostProcessor is an extended interface class of the Spring framework. Through the implementation of this interface, you can do related actions in the process of Bean instantiation, such as intercepting and publishing to the registry. The operation of AOP also establishes contact with the IOC container through BeanPostProcessor. 2.3 BeanFactoryAware

Test class

Public class MyBeanFactoryAware implements BeanFactoryAware {

@ Override

Public void setBeanFactory (BeanFactory beanFactory) throws BeansException {

}

}

Purpose: to get the configuration information of the runtime Bean use: the implementation class of BeanFactoryAware can get the beanFactory, that is, the context information of the bean. At this time, it is very easy for you to get some object properties.

At this point, I believe you have a deeper understanding of "what are the features of Spring IOC?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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