Spring -> @ Import use

@Import by spring-context annotation packet

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
    Class<?>[] value();
}

The annotation is mainly used to import a class configuration (Configuration), normally we create a profile, all within @SpringBootApplication scannable range, and then use that time in the business of this configuration, direct injection can be used normally @Autowired .

As shown above, when we use direct injection of order it is not a problem, since the configuration OrderConfig class, the main class of starting the default scan range.

@SpringBootApplication default scan range, the program starts scanning the current class is the primary package, the package and the current in all sub-packets. If you need to scan the parent package configuration, the need to use starting class @ComponentScan ( "com. **") to indicate the annotation of the package path scanning.

 

If the class is not in the main path configuration where the packet type, and the next sub-packet, as follows:

 In this case, if injected directly into UserConfig, the program will error at startup

Field user in com.example.security.securitydemo.SecurityDemoApplication required a bean of type 'com.example.security.securitydemo.bean.User' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Solution

  1. On startup class plus  @ComponentScan ( "com. **") notes, get directly
  2. Use @Import (UserConfig.class) notes the introduction of

A simple and crude way, directly address the problem, however, this solution, it only suits you know the package name of the class, beginning with the com, org if it is the package name, embarrassing, and on this basis, it is extending a @Import.

@Import equivalent to the original spring xml using <import /> tag, no difference in the two.

 

Guess you like

Origin www.cnblogs.com/idoljames/p/11420029.html