Have a dream, feelings, temperature, dry goods full; Follow me on wechat search [PoXing].

1. The interview questions

Here are some interview questions that can be extended from the passage.

1. Talk about SpringFramework/tell me what you understand about SpringFramework

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

Loosely-coupled: To describe IOC and AOP, it may be possible to extend the IOC loosely-coupled context. Configurable: To pave the way for SpringBoot(convention over configuration) IOC and AOP: Inverse of Control, Aspect Oriented Programming


2. Why use SpringFramework

It can be described as follows:

  1. IOC enables decoupling between components
  2. AOP aspect programming will make the application business unified or specific function enhancement, which can realize the decoupling of application business and enhancement logic
  3. The container manages the beans used in the application, the life cycle of the managed beans, the drivers for events and listening
  4. Web, transaction control, testing, integration with other technologies

3. What modules does SpringFramework contain?

  • Beans, core, Context, expression
  • Aop [aspect programming]
  • JDBC 【 integrate JDBC 】
  • Orm 【 Integrate ORM framework 】
  • Tx 【 Transaction Control 】
  • Web 【 Web Layer Technology 】
  • Test [integrated test]
  • .

Dependency lookup versus dependency injection

target implementation
Dependent lookup (DL) Usually a class member Use context (container)Take the initiative toTo obtain
Dependency Injection (DI) It can be in or out of the method By contextpassiveThe receiving

5. BeanFactory vs. ApplicationContext

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

ApplicationContext is a subinterface to BeanFactory that simplifies integration with AOP, message mechanisms, event mechanisms, and extensions to Web environments (WebApplicationContext, etc.)

ApplicationContext mainly extends the following functions:

  • AOP support (AnnotationAwareAspectJAutoProxyCreatorAfter the Bean is initialized)
  • Configure meta information (BeanDefinitionEnvironmentNotes, etc.)
  • Resource Management (ResourceAbstract)
  • Event-driven mechanism (ApplicationEventApplicationListener
  • Messaging and Internationalization (LocaleResolver
  • EnvironmentAbstraction (after SpringFramework 3.1)

2. History of SpringFramework development

Prior to Spring technology, J2EE emerged. At that time, J2EE had high learning costs, slow development speed, and high performance consumption of developed programs, which could not keep up with the needs of applications at that time. In 2002, Rod Johnson wrote a book called Expert One-on-one J2EE Design and Development, in which he questioned the bloated and inefficient architecture of existing J2EE applications and EJB frameworks. And actively seek and explore solutions.

A simpler solution based on common Java classes and the idea of dependency injection was the seed of the core ideas of the Spring framework

Two years later, SpringFramework 1.0.0 came out in 2004 and Rod Johnson wrote a book ** Expert one-on-one J2EE Development without EJB **, At the time, the book caused a stir in the J2EE development community by telling developers that they could not develop J2EE applications using ejbs at all, and could instead use a lighter and simpler framework called the SpringFramework.

There was a lot of skepticism in the development community at the time, something like this, Nani? Who is this man who questions the design genius of IBM’s many bigwigs? Why the arrogance? Some developers tried to use it, found it was better than EJB, less bloated, improved performance, and provided some features better than EJB, so they slowly moved to the SpringFramework

The update dates and major features of major SpringFramework releases are shown below

SpringFramework version Corresponding JDK version Important features
SpringFramework 1.x JDK 1.3 Xml-based configuration
SpringFramework 2.x JDK 1.4 Improved XML files and initial support for annotated configuration
SpringFramework 3.x Java 5 Annotated configuration, JavaConfig programmatic configuration, Environment abstraction
SpringFramework 4.x Java 6 SpringBoot 1.x, core container enhancement, conditional assembly, WebMvc based on Servlet3.0
SpringFramework 5.x Java 8 SpringBoot 2.x, responsive programming, SpringWebFlux, Kotlin support

3. IOC relies on lookup

Foundation frame construction

  1. Create a Maven module, using IOC-learning as an example

  2. Introduction of depend on

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.8. RELEASE</version>
</dependency>
Copy the code
  1. Creating a Configuration Fileioc-learning-dl.xml

      
   <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
   
   </beans>
Copy the code
  1. Declare a common classPerson.java
public class Person {}Copy the code
  1. ioc-learning-dl.xmlAdding configuration filesPersionThe statement of
<bean id="person" class="com.huodd.bean.Person"></bean>
Copy the code
  1. Creating a startup class
public class DlApplication {
    public static void main(String[] args) {
        // Read configuration files using the BeanFactory interface
        BeanFactory factory = new ClassPathXmlApplicationContext("dl/ioc-learning-dl.xml");
        // Get the object by the id declared in the configuration file
        Person person = (Person) factory.getBean("person"); System.out.println(person); }}Copy the code
  1. Print run
com.huodd.bean.Person@57baeedf
Copy the code

The fully qualified class name + memory address of Person is printed successfully.

3.1 Searching byName Name

Step 6 in the infrastructure above

The core code

Person person = (Person) factory.getBean("person");
Copy the code

3.2 byType Search

1. The ordinary class

  1. Modifying a Configuration Fileioc-learning-dl.xmlpersonIn the statement.idAttributes to remove
<bean class="com.huodd.bean.Person"></bean>
Copy the code
  1. Modifying the 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);
    }
Copy the code

The return value of the Class type is passed directly to the getBean method argument without forcing it

  1. runmainMethod print as follows
com.huodd.bean.Person@61862a7f
Copy the code

2. The interface

  1. Create the interfacedemoDaoAnd implementation classesDemoDaoImpl
public interface DemoDao {
    List<String> findAll(a);
}

public class DemoDaoImpl implements DemoDao{
    @Override
    public List<String> findAll(a) {
        return Arrays.asList("user1"."user2"."user3"); }}Copy the code
  1. Modifying a Configuration Fileioc-learning-dl.xmljoinDemoDaoImplThe statement of
<bean class="com.huodd.dao.DemoDaoImpl"></bean>
Copy the code
  1. Modifying the 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());
    }
Copy the code
  1. runmainMethod The following output is displayed
com.huodd.dao.DemoDaoImpl@7334aada
[user1, user2, user3]
Copy the code

This shows that DemoDaoImpl injection succeeded and that BeanFactory can find the corresponding implementation class based on the interface type

3.3 Advanced Search

OfType Searches for multiple types

If an interface has multiple implementation classes, how do you pull them all out at once? The getBean method used earlier clearly does not suffice to use the ofType method

  1. Create two following the code aboveDemoDaoThe implementation class of
public class DemoMysqlDaoImpl implements DemoDao {
    @Override
    public List<String> findAll(a) {
        return Arrays.asList("mysql_user1"."mysql_user2"."mysql_user3"); }}public class DemoOracleDaoImpl implements DemoDao {
    @Override
    public List<String> findAll(a) {
        return Arrays.asList("oracle_user1"."oracle_user2"."oracle_user3"); }}Copy the code
  1. Modifying a Configuration Fileioc-learning-dl.xmlAdd declarations for the two newly created implementation classes
 <bean class="com.huodd.dao.impl.DemoMysqlDaoImpl"></bean>
 <bean class="com.huodd.dao.impl.DemoOracleDaoImpl"></bean>
Copy the code
  1. Modifying the startup class
public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("dl/ioc-learning-dl.xml");
        Map<String, DemoDao> beans = ctx.getBeansOfType(DemoDao.class);
        beans.forEach((beanName, bean) -> {
            System.out.println(beanName + ":" + bean.toString());
        });

    }
Copy the code

Run the main method and the following output is displayed

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

If you are careful, you may wonder why the return value of the configuration file is read using ApplicationContext instead of BeanFactory

ApplicationContext is also an interface that inherits the BeanFactory from the IDEA diagram

The official article explains:

Org. Springframework. Beans and org. Springframework. The context is the basis of the springframework IOC container. The BeanFactory interface provides an advanced configuration mechanism for managing any type of object. ApplicationContext is a subinterface of the BeanFactory. It adds:

  • Easy integration with SpringFramework AOP functionality
  • Message resource processing (for internationalization)
  • Event publishing
  • Application-layer specific contexts, such as those used in Web applicationsWebApplicationContext

So the ApplicationContext contains all the functionality of the **BeanFactory, ** and extends many more features

The main reason for this is that there is no getBeansOfType() method in BeanFactory

WithAnnotation finds by annotation

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

  1. Create an annotation class
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface animal {
}
Copy the code
  1. Create a few bean objects
@Animal
public class Dog {}@Animal
public class Cat {}public class Xiaoming {}Copy the code

Xiaoming is the only class that doesn’t add @animal

  1. Modify the XML configuration file to add the following three declarations
<bean id="dog" class="com.huodd.bean.Dog"></bean>
<bean id="cat" class="com.huodd.bean.Cat"></bean>
<bean id="xiaoming" class="com.huodd.bean.Xiaoming"></bean>
Copy the code
  1. Modifying the startup class
public class DlApplication {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("dl/ioc-learning-dl.xml");
        Map<String, Object> beans = ctx.getBeansWithAnnotation(Animal.class);
        beans.forEach((beanName, bean) -> {
            System.out.println(beanName + ":"+ bean); }); }}Copy the code
  1. runmainMethod The following output is displayed
dog : com.huodd.bean.Dog@313ac989
cat : com.huodd.bean.Cat@4562e04d
Copy the code

Delay to find

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

Here we start with the XML configuration fileDogThe statement is deleted for now

So when we get dogctx.getBean(Dog.class)Would be an errorNoSuchBeanDefinitionException

  1. The default policy is enabled in the existing scheme
Dog dog;
try {
    dog = ctx.getBean(Dog.class);
} catch (NoSuchBeanDefinitionException e) {
    // Manually create Dog if it cannot be found
    dog = new Dog();
}
System.out.println(dog);
Copy the code

Here we put the business code in a catch block, which is not elegant, the performance could be improved, and it would bea lot of code if every bean was treated this way later

  1. Check under modification before obtaining
 Dog dog = ctx.containsBean("dog")? (Dog) ctx.getBean("dog") : new Dog();
Copy the code

This uses the method in ApplicationContext where containsBean checks to see if the specified bean is present in the container

This method seems to have no problem, but take into account that the parameter passed by this method can only pass the bean ID and cannot be searched according to the bean type. If the bean name is other, the workload is still huge

  1. Use deferred lookup

The idea is that when we want to retrieve a Bean, we are given a wrapper class, and then we “unpack” it to see if the Bean object is there

The usage is as follows

ObjectProvider<Dog> dogProvider = ctx.getBeanProvider(Dog.class);
Copy the code

As you can see, the above code does exactly what we did before, returning a “wrapper” that calls getObject directly when we use it

But if the container is not the Bean or quote NoSuchBeanDefinitionException, the following will introduce ObjectProvider provided by other methods

  • The getIfAvailable() method returns null without throwing an exception if the Bean is not found

    This can be done in the following way

    Dog dog = dogProvider.getIfAvailable(Dog::new);
    Copy the code
  • The ifAvailable() method is used either immediately after the Bean is fetched or intermittently

    The following code

    dogProvider.ifAvailable(dog -> System.out.println(dog)); // Or use method references
    Copy the code

The above is about the SpringFramework and IoC dependency search related content, friends can go to the top of the following questions, whether they can understand and master it.

I am Baoxing, the best time to start doing something is either ten years ago or now. Thank you for your likes, favorites and comments

Article update continuously, you can search wechat [Poxing] for the first time to read