Is Spring so mysterious? —— Brief introduction

1. Introduction to Spring

The composition of the Spring framework

SpringBean concept

In Spring, the objects that form the backbone of the application and are managed by the Spring IoC container are called beans.

Spring container concept

In Spring, objects are created and assembled by the Spring container and stored in the container.

 

Second, the use of Spring

Official Jar package download address: https://repo.spring.io/libs-release-local/org/springframework/spring/

1 Enable component scanning

The @Compont annotation indicates that this class is a component class and tells spring to create a bean for this class.

@CompontScan annotation enables component scanning (it is not enabled by default). If there is no other configuration, it will scan the same package and all sub-packages as the configuration class.

Use XML to enable component scanning and use the <context: compont-scan> element of the Spring context namespace.

2 Declare Bean

@Compont ("<ID>") or @Named ("<ID>") name the bean scanned by the component, the former is recommended.

Set the basic package for component scanning

@CompontScan ("<value>") or @CompontScan (basePackages = "<value>") indicates the name of the package

@CompontScan (basePackages = {"<value1>", "<value2>"}) Set up multiple base packages

3 Assembly Bean

Automatic assembly

@Autowired constructor / Setter method

If there is no matching bean, an exception will be thrown when the context is created.

When the required attribute is set to false, it will not be filled when there is no matching bean. At this time, attention should be paid to the NPE check.

If there are multiple matching beans, Spring throws an exception indicating that there is no explicit choice of which bean to autowire.

The @Inject annotation comes from the Java dependency injection specification and does not depend on Spring.

3. Face the cut

 

Junit

reference

What is spring bean?

Published 19 original articles · Like9 · Visit 3004

Guess you like

Origin blog.csdn.net/Necrolic/article/details/105148422