How to Minimize XML Configuration for Spring

Time:2019-8-8

I. Automatic assembly

1. Four types of automatic assembly

type explain XML configuration
byName Depending on the name or ID of the bean <bean id=”bean” class=”…” autowire=”byName”/>
ByType Automatic assembly according to bean type <bean id=”bean” class=”…” autowire=”byType”/>
contructor According to Bean’s constructor, the input parameters have the same type. Ditto
Autodetect First use contructor, fail and try byType Ditto

There are two ways to avoid errors: 1. Use the primary attribute of < bean > element to set the preferred bean, but the default primary of all beans is true, so we need to set all non-preferred beans to false; 2. Autowi of beans. Re-candidate is familiar with setting false, cancel the candidacy of the bean, and the bean will not be automatically injected.

Contructor auto-assembly has the same limitation as byType. Spring will not try to select one of the constructors when it finds that multiple beans match one of the constructors; moreover, if more than one constructor of a class satisfies the condition of auto-assembly, Spring will not guess which one is more suitable for use.

2. Default automatic assembly

If you need to configure the same autowire attribute for each bean (or most of them) in the Spring application context, you can add a default-autowire attribute to the root element < beans > by default, which is set to none. This property applies only to all beans in the specified configuration file, not all beans in the Spring context.

3. Mixed Automatic Assembly and Explicit Assembly

When we use the automatic assembly strategy for a bean, it does not mean that we can not display and assemble some attributes of the bean. We can configure < property > elements for any attribute. Explicit assembly will cover automatic assembly. But when using the constructor auto-assembly strategy, we must let Spring auto-assembly constructor all the parameters, can not use < constructor-arg > elements for mixing.

II. Annotation Assembly

Starting with Spring 2.5, annotations can be used to automatically assemble Bean properties, annotations allow finer-grained automatic assembly, and optionally annotate a property to apply automatic assembly to it. Spring container disables annotation assembly by default and needs to be enabled in Spring configuration. The simplest way to enable this is to use <context: annotation-config> in Spring’s context command space configuration, as follows:


<beans ...>
<context:annotation-config/>
<!-- bean declarations go here -->
</beans>

Spring 3 supports several different annotations for automatic assembly:

  • Spring’s @Autowire annotation
  • JSR-330’s @Inject annotation
  • JSR-250’s @Resource annotation

1. Use @Autowired

@ Autowire is used to start automatic assembly of ByType for annotated objects and can be used for the following objects:

  • Class attributes, even private attributes can be injected
  • Set method
  • constructor
  • Any method of assembling beans

There are two things that go wrong when using @Autowire: there are no matched beans and there are multiple matched beans, but there are corresponding solutions.

When there is no match bean, automatic assembly throws NoSuchBean Definition Exception. If you don’t want to throw it, you can use the required attribute and set it to false to configure optional automatic assembly, that is, assembly failures will not be assembled and no error will be reported.


@Autowired(required=false)

When configuring with a constructor, only one constructor can set the required property to true and the rest to false. In addition, when annotations are used to annotate multiple constructors, Spring selects the one with the most input from all constructors that satisfy assembly conditions.

Spring also throws a NoSuchBean Definition Exception error when multiple beans satisfy assembly conditions. To select the specified beans, we can use the @Qualifier annotation to filter:

@Autowired
@ Qualifier ("name1")// Screen Beans named name1
private TestClass testClass;

In addition to narrowing the selection scope by using the ID of the bean, we can also narrow the scope by using qualifier directly on the bean, limiting the type of the bean. XML is as follows:


<bean>
<qualifier value="stringed"/>
</bean>

The notes are as follows:


@Qualifier("stringed")
public class xxx{}

You can also create a custom qualifier

To create a custom qualifier, you just need to use the @Qualifier annotation as its source annotation. A Stringed qualifier is created as follows:


@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Stringed{}

Then use it to annotate a Bean:


@Stringed
public class Guitar{}

Then it can be qualified:


@Autowired
@Stringed
private Guitar guitar;

2. Automatic injection using @Inject

In order to unify the programming models of various dependency injection frameworks, the Java dependency injection specification published by JCP (Java Community Process) is called JSR-330. Since Spring 3, Spring has begun to be compatible with the dependency injection model.

Like @Autowire, @Inject can be used to automatically assemble attributes, methods, and constructors. However, @Inject does not have a required attribute, so dependencies must exist, throwing exceptions if they do not exist.

JSR-330 also provides another injection technique, injecting a Provider. Provider interface can implement delayed injection of bean reference and multiple instances of bean injection.

For example, we have a KnifeJuggler class that needs to inject one or more Knife instances. Assuming that the scope of Knife Bean is declared prototype, the following Knife Juggler constructor will get multiple Knife Beans:


private Set<Knife> knifes;
@Inject
public KnifeJuggler(Provider<Knife> knifeProvider){
knives = new HashSet<Knife>();
for(int i=0;i<5;i++){
knives.add(knifeProvider.get());
}
}

Relative to @Qualifier for @Autowire, @Inject corresponds to the @Named annotation. In fact, the @Qualifier annotation is also available in JSR-330, but it is not recommended to use it directly. It is recommended to create custom qualified annotations through this annotation, similar to Spring’s @Qualifier creation process.

3. Use Expressions in Annotations

The @Value attribute introduced in Spring 3 can be used to assemble values of String type and values of base type. With the help of SpEL expressions, @Value can not only assemble hard-coded values, but also dynamically calculate expressions and assemble them at runtime, such as the following:


@Value("#{systemProperties.name}")
private String name;

3. Automatic Bean Detection

Using the <context: annotation-config> mentioned above in Spring, you can achieve automatic assembly, but you still need to declare Bean in xml. Spring also has another element <context: component-scan>, which allows Spring to automatically detect and define beans in addition to completing the function of automatic assembly.


<beans ...>
<context:component-scan base-package="com.springtest">
</context:component-scan>
</beans>

The following annotations are supported after opening:

annotation explain
@Component A generic construct annotation identifying the class as a Spring component
@Controller Identify this class as a Spring MVC controller
@Repository Identify this class as a data warehouse
@Service Identify this class as a service

Using the above annotation, the ID of the bean defaults to an infinite class name. Use @Component (“name”) to specify the ID.

1. Filtration Scanning

By configuring < context: include-filter > and < context: exclude-filter > child elements for context: component-scan, we can adjust the scanning behavior at will. The following configuration automatically registers all TestInterface implementation classes:


<context:component-scan base-package="com.fxb.springtest">
<context:include-filter type="assignable"
expression="com.fxb.springTest.TestInterface"/>
</context:component-scan>

The type and expression attributes work together to define component scanning policies. Type has the following values to choose from:

Type of filter describe
annotation The filter scan uses the classes annotated by the specified annotation. Specify annotations to scan through the expression attribute
assignable Filter scans derive from those classes of the type specified by the expression attribute
aspectj The filter scans the classes that match the AspectJ expression specified by the expression attribute
custom Use a custom org. spring framework. core. type. TypeFilter implementation class, which is specified by the expression attribute
regex The name of the filter scan class matches the regular expression specified by the expression attribute

Exclude-filter is similar to include-filter, but has the opposite effect.

IV. Java-based configuration using Spring

In Spring 3.0, you can configure Spring applications using pure Java code without using XML.

First, you need a very small amount of XML to enable Java configuration, which is the <context: component-scan> mentioned above. The tag also automatically loads the classes identified with the @Configuration annotation

@ Configuration annotations are equivalent to elements in an XML configuration, and this annotation will tell Spring that this class contains one or more definitions of Spring Beans that are annotated using the @Bean annotation

Declare a simple bean code as follows:


@Configuration
public class TestConfig{
@Bean
public Animal duck(){
return new Ducker();
}
}

@ The bean tells Spring that this method will return an object that should be registered as a bean in the Spring application context with the method name as the ID of the bean. It’s also easy to use a reference to another bean, as follows:

@Bean
public Food duckFood(){
return new DuckFood();
}
@ Bean // Referencing a Bean by its method name does not create a new instance
public Animal duck(){
return new Ducker(DuckFood());
}

V. Summary

Finally, I have finished the minimization configuration of Spring, and I have some understanding of the various annotations of Spring. It is not strange to see the annotations before. Although Springboot has helped us to do zero XML configuration now, I think it is necessary to understand the implementation of XML configuration, so as to understand the Java configuration. It will be more profound.

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.