Skip to main content

Spring Framework 概念

1. What is IOC?

  • Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application.
  • Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control.
// 不使用ioc be like
Question q1 = new Question();

// 使用ioc be like
Question q1 = context.getBean(com.chuwa.test.example.Question.class);

2. What is Depency Injection

  • Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”.
  • Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods.
  • Simply put, this allows for loose coupling of components and moves the responsibility of managing components onto the container.

Ways to implement Dependency Injection

  • Constructor Injection (Better one): Constructor injection involves passing dependencies to the constructor of a class. This is a preferred method of DI because it ensures that all required dependencies are available when the object is created. In addition, it also makes it clear what dependencies are required by the class.
  • Setter Injection: Setter injection involves setting the dependencies using setter methods. This is a less preferred method of DI because it makes it less clear what dependencies are required by the class. However, it can be useful in situations where a class has optional dependencies that may not be required in all cases.
  • Field Injection: Field injection involves injecting dependencies directly into the class fields. This is the least preferred method of DI because it makes it unclear what dependencies are required by the class, and it can make unit testing more difficult.

Samples of Constructor Injection

  • Advantages
    • Clear Dependency Relationships: Constructor Injection makes the dependencies of a class more clear, as all required dependencies must be defined in the class constructor. This makes the code more understandable and maintainable.
    • Easy to test: Since all dependencies are explicitly defined in the constructor, it is easy to use mock objects to test the behavior of the class.
    • Immutability: Constructor Injection can make the dependencies of a class immutable. This means that once an object of the class is created, its dependencies cannot be changed, making the code more stable and reliable.
  • Disadvantages
    • Code Duplication
    • Invocation Complexity: Using Constructor Injection may require the class's users to have more knowledge of the internal implementation details. For example, users may need to know how dependencies are constructed and how to properly initialize objects.

UserService 类需要依赖一个 UserRepository 对象,可以通过以下方式使用 Constructor Injection:

public class UserService {
private final UserRepository userRepository;

public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}

OrderService 类需要依赖一个 PaymentService 和一个 ShippingService 对象,可以通过以下方式使用 Constructor Injection:

public class OrderService {
private final PaymentService paymentService;
private final ShippingService shippingService;

public OrderService(PaymentService paymentService, ShippingService shippingService) {
this.paymentService = paymentService;
this.shippingService = shippingService;
}
}

3. What is bean life cycle?

The bean life cycle refers to when & how the bean is instantiated, what action it performs until it lives, and when & how it is destroyed.

简化的 Spring Bean 生命周期的概述:

  1. 实例化 Instantiation:创建 Bean 对象。
  2. 属性填充 Populating properties:为 Bean 设置属性和依赖。
  3. 初始化 Initialization:执行 Bean 初始化逻辑。
  4. Bean 可用 Bean is ready for use:Bean 已准备好供应用程序使用。
  5. 销毁 Bean is destroyed:当应用程序或容器关闭时,销毁 Bean。

4. How many ways to define a bean?

  1. Creating Bean Inside an XML Configuration File (beans.xml)
<!-- eg. -->
<bean id="AnyUniqueId" class="YourClassName">
</bean>
  1. Using @Component Annotation

At runtime, Spring finds all classes annotated with @Component or its derivatives and uses them as bean definitions. The process of finding annotated classes is called component scanning.

The list of @Component derivatives includes:

  • @Service
  • @Repository
  • @Controller
// eg.
@Component
class MySpringBeanClass {
//...
}
  1. Using @Bean Annotation

For classes you don’t own, you have to create factory methods with the @Bean annotation in a custom bean configuration class.

// eg.
@Configuration
class MyConfigurationClass {

@Bean
public NotMyClass notMyClass() {
return new NotMyClass();
}

}

5. How to tell Spring Framework to find the beans?

@ComponentScan

6. What is the bean's default name?

  • The default bean name is @Bean annotated method name.
  • From the example of a concrete service implementation, com.xyz.FooServiceImpl -> fooServiceImpl

7. How many way to wire a bean to variable?

  • Spring provides three ways of Dependency Injection to wire a bean to variable:
    • Constructor based Dependency Injection.
    • Setter based Dependency Injection.
    • Field or property based Dependency Injection.
  • Constructor based Dependency Injection is recommended.

8. What kind of bean scope do you know in Spring? And what is the difference?

  • Singleton: This scopes the bean definition to a single instance per Spring IoC container (default).
  • Prototype: This scopes a single bean definition to have any number of object instances.
  • Request
  • Session
  • Global-Session

9. Do you know AOP 面向切面编程?

AOP (Aspect-Oriented Programming) is a programming pattern that increases modularity by allowing the separation of the cross-cutting concern. These cross-cutting concerns are different from the main business logic. Examples of cross-cutting concerns: Logging, Security, validation, caching, etc.

10. Different between @Bean and @Service?

  • @Bean is used in a configuration class. @Bean marks that the method returns a bean.
  • @Service indicates the annotated class is a "service". The class will be discovered by the spring framework and a bean will be instantialized.