Spring Fundamentals Summary - Essential Reading for Java Developers
Category Programming Technology
Introduction to Spring
The Spring framework was developed by Rod Johnson and released its first version in 2004. Spring is a framework abstracted from actual development practices, completing many common steps in development, leaving developers only with parts specific to the application, thus significantly improving the efficiency of enterprise application development.
The advantages of Spring can be summarized as follows:
Low-invasive design, with minimal code pollution.
Independent of various application servers, applications based on the Spring framework can truly fulfill the promise of "Write Once, Run Anywhere."
Spring's IoC container reduces the complexity of replacing business objects and enhances decoupling between components.
Spring's AOP support allows for centralized management of common tasks such as security, transactions, and logging, providing better reusability.
Spring's ORM and DAO facilitate good integration with third-party persistence frameworks and simplify underlying database access.
Spring's high openness does not force applications to fully depend on Spring; developers can freely choose to use part or all of the Spring framework.
The composition structure of the Spring framework is shown below:
In addition to this, the factory-method
attribute needs to be used to specify the static factory method, which Spring will call to return a Bean instance. Once the specified Bean instance is obtained, Spring's subsequent processing steps are exactly the same as those for creating a Bean instance using a regular method. If the static factory method requires parameters, use the <constructor-arg.../>
element to specify the parameters for the static factory method.
Creating Bean with Instance Factory Method
The instance factory method differs from the static factory method in only one aspect: invoking a static factory method requires only the factory class, while invoking an instance factory method requires a factory instance. When using an instance factory method, the <bean.../>
element for configuring the Bean instance does not need a class
attribute. The instance factory method is configured using the factory-bean
attribute to specify the factory instance. The <bean.../>
element needs to specify the following two attributes:
factory-bean
: The value of this attribute is the id of the factory Bean.factory-method
: This attribute specifies the factory method of the instance factory.
If parameters need to be passed when invoking the instance factory method, use the <constructor-arg.../>
element to determine the parameter values.
Coordinating Beans with Different Scopes
When a singleton-scoped Bean depends on a prototype-scoped Bean, synchronization issues may arise because the Spring container pre-initializes all singleton Beans
during its initialization. Since the singleton Bean
depends on the prototype Bean
, Spring creates the prototype Bean
before creating the singleton Bean
, and then injects the prototype Bean
into the singleton Bean
.
Abandon dependency injection: Each time the singleton-scoped Bean needs the prototype-scoped Bean, it actively requests a new instance from the container, ensuring that the injected
prototype Bean
is always the latest instance.Utilize method injection: Method injection typically uses lookup method injection. This allows the Spring container to override abstract or concrete methods of a Bean in the container, returning the result of looking up another Bean. The looked-up Bean is usually a
non-singleton Bean
. Spring achieves this by using JDK dynamic proxies or the cglib library to modify the client's binary code.
It is recommended to use the second method, method injection. To use lookup method injection, roughly the following two steps are needed:
Define the caller Bean's implementation class as an abstract class and define an abstract method to obtain the dependent Bean.
Add a
<lookup-method.../>
sub-element in the<bean.../>
element to have Spring implement the specified abstract method for the caller Bean's implementation class.
>
Spring will dynamically enhance the abstract method specified by the <lookup-method.../>
element at runtime. If the target abstract class implements an interface, Spring will use JDK dynamic proxies to implement the abstract class and its abstract method; if the target abstract class does not implement an interface, Spring will use cglib to implement the abstract class and its abstract method. The cglib library is integrated in the spring-core-xxx.jar package of Spring 4.0.
Two Types of Post-Processors
Spring provides two commonly used post-processors:
Bean post-processor: This post-processor performs post-processing on Beans in the container, enhancing them with additional features.
Container post-processor: This post-processor performs post-processing on the IoC container, enhancing its functionality.
Bean Post-Processor
A Bean post-processor is a special type of Bean that does not provide services externally; it may not even need an id attribute. It primarily handles post-processing for other Beans in the container, such as generating proxies for target Beans, and is referred to as a Bean post-processor. A Bean post-processor will further enhance the Bean instance after it has been successfully created. A Bean post-processor must implement the BeanPostProcessor
interface and its two methods.
Object postProcessBeforeInitialization(Object bean, String name) throws BeansException
: The first parameter of this method is the Bean instance that the system is about to post-process, and the second parameter is the configuration id of the Bean.Object postProcessAfterInitialization(Object bean, String name) throws BeansException
: The first parameter of this method is the Bean instance that the system is about to post-process, and the second parameter is the configuration id of the Bean.
Once a Bean post-processor is registered in the container, it automatically activates and works automatically when each Bean is created in the container. The callback timing of the two methods of the Bean post-processor is as follows:
Note that if BeanFactory
is used as the Spring container, the Bean post-processor must be registered manually. The program must obtain the Bean post-processor instance and register it manually.
BeanPostProcessor bp = (BeanPostProcessor)beanFactory.getBean("bp");
beanFactory.addBeanPostProcessor(bp);
Person p = (Person)beanFactory.getBean("person");
Container Post-Processor
A Bean post-processor handles all Bean instances in the container, while a container post-processor handles the container itself. A container post-processor must implement the BeanFactoryPostProcessor
interface and its method postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
. The method body of this method is the processing of the Spring container, which can customize and extend the Spring container, or it can choose not to process the Spring container at all.
Similar to BeanPostProcessor
, ApplicationContext
can automatically detect and register container post-processors in the container. However, if BeanFactory
is used as the Spring container, the container post-processor must be manually invoked to process the BeanFactory
container.
Spring's "Zero Configuration" Support
Searching for Bean Classes
Spring provides several annotations to mark Spring Beans:
@Component
: Marks a normal Spring Bean class.@Controller
: Marks a controller component class.@Service
: Marks a business logic component class.@Repository
: Marks a DAO component class.
Configure the following in the Spring configuration file to specify the package to be automatically scanned:
<context:component-scan base-package="edu.shu.spring.domain"/>
Using @Resource to Configure Dependencies
@Resource
is located in the javax.annotation
package and is an annotation from the JavaEE specification. Spring directly adopts this annotation to specify collaborators for the target Bean. Using @Resource
has the same effect as the ref
attribute of the <property.../>
element. @Resource
can not only modify setter methods but also directly modify instance variables. If @Resource
is used to modify an instance variable, it will be even simpler, as Spring will directly use Field injection from the JavaEE specification, and even the setter method can be omitted.
Using @PostConstruct and @PreDestroy to Customize Lifecycle Behavior
@PostConstruct
and @PreDestroy
are also located in the javax.annotation
package and are annotations from the JavaEE specification. Spring directly adopts them to customize the lifecycle behavior of Beans in the Spring container. They are both used to modify methods and do not require any attributes. The method modified by the former is the initialization method of the Bean; the method modified by the latter is the method before the Bean is destroyed.
Enhanced Autowiring and Precise Autowiring in Spring 4.0
Spring provides the @Autowired
annotation to specify autowiring. @Autowired
can modify setter methods, ordinary methods, instance variables, and constructors. When @Autowired
is used to annotate a setter method, it defaults to using the byType autowiring strategy. In this strategy, there are often multiple candidate Bean instances that match the autowired type, which may cause exceptions. To achieve precise autowiring, Spring provides the @Qualifier
annotation, which allows autowiring based on the Bean's id.
Spring's AOP
Why AOP is Needed
AOP (Aspect Orient Programming) is a programming paradigm as a supplement to object-oriented programming and has become a relatively mature programming approach. In fact, the advent of AOP is not too long. AOP complements OOP and decomposes the program execution process into various aspects.
AOP is specifically used to address cross-cutting concerns distributed across various modules (different methods) in the system. In JavaEE applications, AOP is often used to handle some system-level services with cross-cutting nature, such as transaction management, security checks, caching, object pool management, etc. AOP has become a very common solution.
Implementing AOP with AspectJ
AspectJ is an AOP framework based on the Java language, providing powerful AOP functionality, with many other AOP frameworks drawing inspiration or adopting its ideas. It mainly includes two parts: one part defines the syntax specification for expressing and defining AOP programming. With this syntax specification, it is convenient to use AOP to solve the cross-cutting concerns in the Java language; the other part is the tool part, including compilers, debuggers, etc.
AOP implementations can be divided into two categories:
Static AOP implementation: The AOP framework modifies the program at the compilation stage, i.e., enhances the target class, generating a static AOP proxy class, represented by AspectJ.
Dynamic AOP implementation: The AOP framework dynamically generates AOP proxies at runtime to enhance the target object, represented by Spring AOP.
Generally, static AOP implementations have better performance but require a special compiler. Dynamic AOP implementations are purely Java implementations, so no special compiler is needed, but they usually have slightly worse performance.
Basic Concepts of AOP
Some terminology about aspect-oriented programming:
Aspect: An aspect organizes multiple advices, with advices defined within the aspect.
Joinpoint: A specific point in the program execution, such as a method call or an exception thrown. In Spring AOP, a joinpoint is always a method call.
Advice: The enhancement processing performed by the AOP framework at a specific joinpoint. There are types like "around," "before," and "after."
Pointcut: A joinpoint where enhancement processing can be inserted. In other words, when a certain joinpoint meets specified requirements, it will be added with enhancement processing, turning it into a pointcut.
AOP Support in Spring
AOP proxies in Spring are generated and managed by the Spring IoC container, with their dependencies also managed by the IoC container. @AspectJ
support requires adding three libraries to Spring:
aspectjweaver.jar
aspectjrt.jar
aopalliance.jar
And configure the following in the Spring configuration file:
<!--Enable @AspectJ support-->
<aop:aspectj-autoproxy/>
<!--Specify automatic search for Bean components, automatic search for aspect classes-->
<context:component-scan base-package="edu.shu.sprint.service">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
Source: http://codepub.cn/2015/06/21/Basic-knowledge-summary-of-Spring/
#
-
** Haha
* che**26.com
@Resource and @Autowired, the differences between them, @Resource is from the javax.annotation.Resource package, supported by JavaEE; @Autowired is from the org.springframework.beans.factory.annotation.Autowired package, provided by Spring. This makes @Resource more extensible than @Autowired because when exporting a project, using the @Resource annotation can be provided by the Java environment, while using the @Autowired annotation requires additional introduction of the Spring package.
** Haha
* che**26.com
** Click to share notes
-
-
- ```