当前位置:网站首页>About note 1

About note 1

2022-04-23 13:50:00 It only supports modification once a month

One . Definition of annotations

 All defined annotations implement... By default Annotation Interface , Just like all classes inherit by default Object class , The defined annotation has at least 2 An annotation is used to specify the usable range and operation range of the annotation 

 Use annotations for classes or methods , When called normally, it has no effect , Only when called by reflection , It will work ( Reflection deals with annotations )

@Override annotation 

@Taeget annotation   Appoint Annotations can be used   Location

METHOD It can be used in methods
PARAMETER Available on parameters
CONSTRUCTOR It can be used in construction methods
LOCAL_VARIABLE Can be used on local variables
ANNOTATION_TYPE Can be used on annotation types ( By interface The type of embellishment )
PACKAGE Used to record java Of documents package Information
ANNOTATION_TYPE Can be used on annotation types ( By interface The type of embellishment )

@Retention(RetentionPolicy.RUNTIME) Must specify   Operating range    RUNTIME( This will be reflected to get )


Two . Use of annotations

springboot The central note : 

@SpringBootApplication = ( The default attribute )@Configuration 
                       + @EnableAutoConfiguration
                       + @ComponentScan.

@Configuration  Used to define the configuration class , alternative XML The configuration file , The annotated class contains one or more @Bean Annotation method .

@Bean Annotations tell Spring, With a @Bean The annotation method returns an object , The object should be registered at Spring In the context of the application bean.

@EnableAutoConfiguration: Can automatically configure spring The context of , Try to guess and configure what you want bean class , Usually automatically based on your classpath and your bean Define auto configuration .

@ComponentScan: Meeting Automatically scan the specified package All are marked with @Component Class , And register into bean, Including, of course @Component Next sub note @Service,@Repository,@Controller

Two .@Component and @Bean There are two ways to use annotations to define bean The way

@Component Declarative . be responsible for Create real example ( That is to say bean) and Deposit in IOC Containers ,  @Autowired Take out Instance injection into reference

web Development , Provide 3 Replace @Component A derivative of an annotation ( Function as , It's all creation bean, Put in container )
        @Repository(“ name ”):dao layer
        @Service(“ name ”):service layer
        @Controller(“ name ”):web layer

        @service Annotation itself has two responsibilities :
         One is Bean The creation of ; You can use @Component Instead of
         The second is to identify a class as a service .

         @Component The object instantiated by annotation is singleton by default , If you want to declare multiple objects, you can use  

                @Component
                @Scope("prototype")

        @Repository Default singleton ( To be verified )

        @Service Default singleton ( To be verified )

        @Controller The default is multiple cases ( To be verified )


@Bean Used to explicitly declare a single bean, Rather than let Spring Automatically execute it as above . It will bean The declaration of is separated from the class definition , And allows you to accurately create and configure bean.(@Bean It is convenient to declare an object ,)

@Configuration Added by spring management The singleton pattern  @Configuration It's a singleton

@Bean Annotation ratio @Component Annotations are more user-defined , And a lot of places can only go through @Bean Annotation to register bean. For example, when a class that references a third-party library needs to be assembled into Spring Container time , You can only go through @Bean Annotation to implement

  3、 ... and .@Resource And @Autowired

1.   @Autowired by Spring Notes provided , Package import required org.springframework.beans.factory.annotation.Autowired.

     @Resource Comments by J2EE Provide , Package import required javax.annotation.Resource

2.@Resource Is equivalent to @Autowired, It's just @Autowired Press byType Automatic injection , and @Resource Press default byName Automatic injection

@Autowired It is automatically assembled according to the type . If so Spring More than one in context UserDao Type of bean when , Will throw BeanCreationException abnormal ; If Spring There is no... In the context UserDao Type of bean,

It will also be thrown out BeanCreationException abnormal . We can use @Qualifier coordination @Autowired To solve these problems  

@Qualifier tell spring Which object to assemble

Four . @Value Annotations use

Usually use The first way @Value(“${}”) Read the value of the configuration file (application.properties or application.yml)

Code

The configuration file

The second kind @Value("#{}")  Spring Expression language ( abbreviation SpEL)


5、 ... and .@PostConstruct

By @PostConstruct The decorated method will be loaded on the server Servlet Run when , And will only be executed once by the server

Constructor > @Autowired > @PostConstruct

//------------------------------------------------------------------------------------------------------------------

 6、 ... and . @Around
  • You can decide when the target method is executed , How to execute , It can even completely prevent the execution of the target method ;
  • You can change the parameter values of the target method , You can also change the return value after executing the target method ; When you need to change the return value of the target method , Only use Around Method   It usually needs to be used in a thread safe environment
  • <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

//------------------------------------------------------------------------------------------------------------------

@ConditionalOnProperty To control Configuration Whether to take effect

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    String[] value() default {}; // Array , Get corresponding property The value of the name , And name Do not use at the same time   
  
    String prefix() default "";//property Prefix of name , not essential   
  
    String[] name() default {};// Array ,property A full or partial name ( But with prefix Use a combination of , Make up the whole property name ), And value Do not use at the same time   
  
    String havingValue() default "";// But with name Use a combination of , Compare the obtained property value with havingValue Is the given value the same , The same load configuration   
  
    boolean matchIfMissing() default false;// This is missing property Can I load . If true, There is no the property It will also load normally ; On the contrary, report an error   
  
    boolean relaxedNames() default true;// Whether it can be loosely matched , I don't know how to use it   
} 
}

// stay application.properties To configure     framework.swagger.enable=true

Through its two properties name as well as havingValue To achieve , among name Used to from application.properties Reads an attribute value in .
If the value is null , Then return to false;
If the value is not null , Will be the value of havingValue The specified value is compared , Returns if it is the same true; Otherwise return to false.
If the return value is false, Then configuration Don't take effect ; by true Is to take effect .

@Configuration
// stay application.properties To configure "framework.swagger.enable", The corresponding value is true
@ConditionalOnProperty(prefix="framework.swagger",name = "enable", havingValue = "true")
public class SwaggerConfig {
    @Autowired
    private HelloServiceProperties helloServiceProperties;
    @Bean
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}

//------------------------------------------------------------------------------------------------------------------

@ConfigurationProperties("jwt")

//------------------------------------------------------------------------------------------------------------------

Custom annotation :

//------------------------------------------------------------------------------

spring.factories Load instances first

Spring Factories Realization principle

spring-core It's defined in the package SpringFactoriesLoader class , This class implements Retrieval META-INF/spring.factories file , And get the configuration function of the specified interface . Two external methods are defined in this class :

loadFactories Get the instance of its implementation class according to the interface class , This method returns a list of objects .
loadFactoryNames Get the name of the interface class according to the interface , This method returns a list of class names .
The key to both of the above methods is from the specified ClassLoader In order to get spring.factories file , And parse to get a list of class names , The specific code is as follows

    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = cache.get(classLoader);
        if (result != null) {
            return result;
        }

        try {
            Enumeration<URL> urls = (classLoader != null ?
                    classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                    ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
            result = new LinkedMultiValueMap<>();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                for (Map.Entry<?, ?> entry : properties.entrySet()) {
                    String factoryClassName = ((String) entry.getKey()).trim();
                    for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                        result.add(factoryClassName, factoryName.trim());
                    }
                }
            }
            cache.put(classLoader, result);
            return result;
        }
        catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load factories from location [" +
                    FACTORIES_RESOURCE_LOCATION + "]", ex);
        }
    }

We can see from the code that , In this method, the entire ClassLoader All in jar Under bag spring.factories file . In other words, we can be in our own jar Middle configuration spring.factories file , It won't affect the configuration of other places , It will not be covered by other people's configuration .

spring.factories It's through Properties The analytic result is , So the content in the file we write is configured in the following way :

com.xxx.interface=com.xxx.classname

In daily work , We may need to implement some SDK perhaps Spring Boot Starter When used by others ,
We can use Factories Mechanism .Factories The mechanism can make SDK perhaps Starter The use of requires little or no configuration , Just introduce our... Into the service jar Bag can


 

spring The role of annotations :

//----------------------------------------------------------------

@Documented 

When customizing annotations, you can use @Documented To mark , If you use @Documented Marking the , It's generating javadoc When you do, you will put @Documented The annotations are shown .

Keep in mind , Just use annotations , There must be Trigonometry :

  • Definition annotation
  • Use annotation
  • Read annotation

Just complete the first two steps , It's useless . It's like you wrote a martial arts secret book, but no one learned it , Then this martial art is not as good as a kitchen knife .

There is more than one way to read annotations .

版权声明
本文为[It only supports modification once a month]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230556158347.html