zoukankan      html  css  js  c++  java
  • SpringIOC常用注解

    1.1、@Configuration:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Configuration {
    
    	/**
    	 * Explicitly specify the name of the Spring bean definition associated with the
    	 * {@code @Configuration} class. If left unspecified (the common case), a bean
    	 * name will be automatically generated.
    	 * <p>The custom name applies only if the {@code @Configuration} class is picked
    	 * up via component scanning or supplied directly to an
    	 * {@link AnnotationConfigApplicationContext}. If the {@code @Configuration} class
    	 * is registered as a traditional XML bean definition, the name/id of the bean
    	 * element will take precedence.
    	 * @return the explicit component name, if any (or empty String otherwise)
    	 * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
    	 */
    	@AliasFor(annotation = Component.class)
    	String value() default "";
    
    }
    

    它是在spring3.0版本之后加入的。此注解是spring支持注解驱动开发的一个标志。表明当前类是spring的一个配置类,作用是替代spring的applicationContext.xml。但其本质就是@Component注解,被此注解修饰的类,也会被存入spring的ioc容器。

    • value:表名存入Spring容器中的Bean的ID。

    1.2、@ComponentScan:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    @Repeatable(ComponentScans.class)
    public @interface ComponentScan {
    	/**
    	 */
    	@AliasFor("basePackages")
    	String[] value() default {};
    
      	/**
    	 */
    	@AliasFor("value")
    	String[] basePackages() default {};
    
      	/**
    	 */
    	Class<?>[] basePackageClasses() default {};
    
      	/**
    	 */
    	Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
    
      	/**
    	 */
    	Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;
    
      	/**
    	 */
    	ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;
    
      	/**
    	 */
    	String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;
    
      	/**
    	 */
    	boolean useDefaultFilters() default true;
    
      	/**
    	 */
    	Filter[] includeFilters() default {};
    
      	/**
    	 */
    	Filter[] excludeFilters() default {};
    
      	/**
    	 */
    	boolean lazyInit() default false;
    
    
    	/**
    	 * Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters
    	 * include filter} or {@linkplain ComponentScan#excludeFilters exclude filter}.
    	 */
    	@Retention(RetentionPolicy.RUNTIME)
    	@Target({})
    	@interface Filter {
    		/**
    		 */
    		FilterType type() default FilterType.ANNOTATION;
    
    		/**
    		 */
    		@AliasFor("classes")
    		Class<?>[] value() default {};
          
    		/**
    		 */
    		@AliasFor("value")
    		Class<?>[] classes() default {};
          
    		/**
    		 */
    		String[] pattern() default {};
    	}
    }
    

    用于指定创建容器时要扫描的包。该注解在指定扫描的位置时,可以指定包名,也可以指定扫描的类。同时支持定义扫描规则,例如包含哪些或者排除哪些。同时,它还可以通过nameGenerator自定义Bean的命名规则

    • value:用于指定要扫描的包。当指定了包的名称之后,spring会扫描指定的包及其子包下的所有类。

    • basePackages:它和value作用是一样的。

    • basePackageClasses:指定具体要扫描的类的字节码。

    • nameGenrator:指定扫描bean对象存入容器时的命名规则。默认情况下注入到IOC中的Bean的名称为类名的首字母小写。

    • scopeResolver:用于处理并转换检测到的Bean的作用范围。

    • soperdProxy:用于指定bean生成时的代理方式。

    • resourcePattern: 用于指定符合组件检测条件的类文件,默认是包扫描下的 **/*.class,即Spring会扫描打上了@ComponentScan注解的类所在包以及子包下的所有类文件。

    • useDefaultFilters:是否对带有@Component @Repository @Service @Controller注解的类开启检测,默认是开启的。

    • includeFilters:自定义组件扫描的过滤规则,用以扫描组件。FilterType有5种类型:

      • ANNOTATION:注解类型,也是默认的类型
      • ASSIGNABLE_TYPE:指定固定类
      • ASPECTJ:ASPECTJ类型
      • REGEX:正则表达式
      • CUSTOM:自定义类型
    • excludeFilters:自定义组件扫描的排除规则。

    • lazyInit:组件扫描时是否采用懒加载 ,默认不开启。

    ​ 在spring4.3版本之后还加入了一个@ComponentScans的注解,该注解可以支持配置多个@ComponentScan。

    1.3、 @Bean

    @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Bean {
    	/**
    	 */
    	@AliasFor("name")
    	String[] value() default {};
      
    	/**
    	 */
    	@AliasFor("value")
    	String[] name() default {};
    
      	/**
    	 */
    	@Deprecated
    	Autowire autowire() default Autowire.NO;
    
      	/**
    	 */
    	boolean autowireCandidate() default true;
    
      	/**
    	 */
    	String initMethod() default "";
    
      	/**
    	 */
    	String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
    }	
    

    @Bean通常出现在Spring的配置类当中,注解在方法上,表示把当前方法的返回值存入spring的ioc容器。

    同时还可以出现在注解上,作为元注解来使用。

    • value:用于指定存入spring容器中bean的标识。支持指定多个标识。当不指定该属性时,默认值是当前方法的名称。

    • name:同value作用一样

    • autowireCandidate:用于指定是否支持自动按类型注入到其他bean中。只影响@Autowired注解的使用。不影响@Resource注解注入。默认值为true,意为允许使用自动按类型注入。

    • initMethod:指定Bean的初始化方法

    • destroyMethod:指定Bean的销毁方法

    1.4、@Import

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

    该注解是写在类上的,通常都是和注解驱动的配置类一起使用的。其作用是引入其他的配置类。使用了此注解之后,可以使我们的注解驱动开发和早期xml配置一样,分别配置不同的内容,使配置更加清晰。同时指定了此注解之后,被引入的类上可以不再使用@Configuration,@Component等注解。通常情况可以使用@Import注解导入以下三种类

    1. 导入@Configuration注解的配置类;
    2. 导入ImportSelector的实现类;
    3. 导入ImportBeanDefinitionRegistrar的实现类;

    如果需要导入其他类或者导入xml更推荐使用@ImportResource

    1.5、@PropertySource

    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Repeatable(PropertySources.class)
    public @interface PropertySource {
    
    	/**
    	 */
    	String name() default "";
    
    	/** 
    	 */
    	String[] value();
    
    	/** 
    	 */
    	boolean ignoreResourceNotFound() default false;
    
    	/**
    	 */
    	String encoding() default "";
    
    	/**
    	 */
    	Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
    
    }
    

    用于指定读取资源文件的位置。注意,它不仅支持properties,也支持xml文件,并且通过YAML解析器,配合自定义PropertySourceFactory实现解析yml配置文件

    • name:指定资源的名称。如果没有指定,将根据基础资源描述生成。
    • value:指定资源的位置。可以是类路径,也可以是文件路径。
    • ignoreResourceNotFound:没有找到资源文件是否忽略,默认是false,也就是说当资源文件不存在时spring启动将会报错。
    • encoding:指定解析资源文件使用的字符集。
    • factory:指定读取对应资源文件的工厂类,默认的是PropertySourceFactory。

    1.6、DependsOn

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface DependsOn {
    	String[] value() default {};
    }
    

    @DependsOn用于指定某个Bean的创建需要依赖其它Bean。spring中没有特定bean的加载顺序,使用此注解则可指定bean的加载顺序。

    • value:需要依赖的Bean的名称

    1.7、@Lazy

    @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Lazy {
    	boolean value() default true;
    }
    

    用于指定单例bean对象的创建时机。在没有使用此注解时,单例bean的生命周期与容器相同。也就是容器创建后会将所有的单例Bean创建好放入容器中,但是当使用了此注解之后,单例对象的创建时机变成了第一次使用时创建。注意@Lazy只对单例Bean起作用。

    • value:指定是否采用延迟加载。默认值为true,表示开启。

    1.8@Conditional

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented	
    public @interface Conditional {
    
    	/**
    	 * All {@link Condition Conditions} that must {@linkplain Condition#matches match}
    	 * in order for the component to be registered.
    	 */
    	Class<? extends Condition>[] value();
    }	
    

    它的作用是根据条件选择是否像容器中注入的bean对象。SpringBoot中大量的用到了此注解及其衍生的注解

    • value:用于提供一个Condition接口的实现类,实现类中需要编写具体代码实现注入的条件。
    @FunctionalInterface
    public interface Condition {
    
       /**
        * Determine if the condition matches.
        * @param context the condition context
        * @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
        * or {@link org.springframework.core.type.MethodMetadata method} being checked
        * @return {@code true} if the condition matches and the component can be registered,
        * or {@code false} to veto the annotated component's registration
        */
       boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
    
    }
    

    当matches方法返回true表示向容器中注入Bean,返回false不向容器中注入Bean

    1.8、@Component@Controller@Service@Repository

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Indexed
    public @interface Component {
    
    	/**
    	 * The value may indicate a suggestion for a logical component name,
    	 * to be turned into a Spring bean in case of an autodetected component.
    	 * @return the suggested component name, if any (or empty String otherwise)
    	 */
    	String value() default "";
    }
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Controller {
    
    	/**
    	 * The value may indicate a suggestion for a logical component name,
    	 * to be turned into a Spring bean in case of an autodetected component.
    	 * @return the suggested component name, if any (or empty String otherwise)
    	 */
    	@AliasFor(annotation = Component.class)
    	String value() default "";
    
    }
    
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Service {
    
    	/**
    	 * The value may indicate a suggestion for a logical component name,
    	 * to be turned into a Spring bean in case of an autodetected component.
    	 * @return the suggested component name, if any (or empty String otherwise)
    	 */
    	@AliasFor(annotation = Component.class)
    	String value() default "";
    
    }
    
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Repository {
    
    	/**
    	 * The value may indicate a suggestion for a logical component name,
    	 * to be turned into a Spring bean in case of an autodetected component.
    	 * @return the suggested component name, if any (or empty String otherwise)
    	 */
    	@AliasFor(annotation = Component.class)
    	String value() default "";
    
    }
    

    以上四个注解都是用在类上,表名当前类需要创建对象并且存入spring的ioc容器中。在实例化时,首选默认无参构造函数。同时支持带参构造,前提是构造函数的参数依赖必须要有值,否则抛异常。在MVC开发中,@Controller在控制层使用,@Service在服务层使用,@Repository在持久层使用。

    • value:用于指定存入容器时bean的id。当不指定时,默认值为当前类的名称首字母小写。

    1.8、@Autowired

    @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Autowired {
    
    	/**
    	 * Declares whether the annotated dependency is required.
    	 * <p>Defaults to {@code true}.
    	 */
    	boolean required() default true;
    
    }
    

    自动按照类型注入。当ioc容器中有且只有一个类型匹配时可以直接注入成功。当有超过一个匹配时,则使用变量名称(写在方法上就是方法名称)作为bean的id,在符合类型的bean中再次匹配,能匹配上就可以注入成功。当匹配不上时,是否报错要看required属性的取值。

    • required:是否必须注入成功。默认值是true,表示必须注入成功。当取值为true的时候,注入不成功会报错。

    1.9、@Qualifier

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface Qualifier {
    
    	String value() default "";
    
    }
    

    当使用自动按类型注入时,遇到有多个类型匹配的时候,就可以使用此注解来明确注入哪个bean对象。注意它通常情况下和@Autowired注解一起使用

    • value:指定匹配Bean的名称

    1.10、@Resource

    @Target({TYPE, FIELD, METHOD})
    @Retention(RUNTIME)
    public @interface Resource {
    
        String name() default "";
    
        String lookup() default "";
    
        Class<?> type() default java.lang.Object.class;
    
        enum AuthenticationType {
                CONTAINER,
                APPLICATION
        }
    
        AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
    
        boolean shareable() default true;
    
        String mappedName() default "";
    
        String description() default "";
    }
    

    此注解来源于JSR-250规范(Java Specification Requests),其作用是找到依赖的组件注入到应用中来,它利用了JNDI(Java Naming and Directory Interface Java命名目录接口 J2EE规范之一)技术查找所需的资源。
    默认情况下,即所有属性都不指定,它默认按照byType的方式装配bean对象。如果指定了name,没有指定type,则采用byName。如果没有指定name,而是指定了type,则按照byType装配bean对象。当byName和byType都指定了,两个都会校验,有任何一个不符合条件就会报错。

    • name:资源的JNDI名称。在spring的注入时,指定bean的唯一标识。
    • type:指定bean的类型。
    • lookup:引用指向的资源的名称。它可以使用全局JNDI名称链接到任何兼容的资源。
    • authenticationType:指定资源的身份验证类型。它只能为任何受支持类型的连接工厂的资源指定此选项,而不能为其他类型的资源指定此选项。
    • shareable:指定此资源是否可以在此组件和其他组件之间共享。
    • mappedName:指定资源的映射名称。
    • description:指定资源的描述。

    简单理解可以把@Resource当作@Autowired@Qualifier的合体版。

    1.11、@Value

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Value {
    
    	/**
    	 * The actual value expression: for example {@code #{systemProperties.myProp}}.
    	 */
    	String value();
    
    }
    

    用于注入基本类型和String类型的数据。它支持spring的EL表达式,可以通过${} 的方式获取配置文件中的数据。配置文件支持properties,xml和yml文件。

    • value:指定注入的数据或者spring的el表达式。

    1.12、@Inject

    @Target({ METHOD, CONSTRUCTOR, FIELD })
    @Retention(RUNTIME)
    @Documented
    public @interface Inject {
    }
    

    它也是用于建立依赖关系的。和@Resource和@Autowired的作用是一样。在使用之前需要先导入坐标:

    <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    

    @Inject来源于`JSR-330规范。(JSR330是Jcp给出的官方标准反向依赖注入规范。)
    它不支持任何属性,但是可以配合@Qualifier或者@Primary注解使用。
    同时,它默认是采用byType装配,当指定了JSR-330规范中的@Named注解之后,变成byName装配。

    1.13、@Named

    @Qualifier
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Named {
        String value() default "";
    }
    

    通常配合@Inject使用,在自动注入时用来指定注入Bean的名称

    • value:要注入的Bean的名称

    1.14、@Primary

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Primary {
    
    }
    

    用于指定bean的注入优先级。被@Primary修饰的bean对象优先注入

    1.15、@Scope

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Scope {
    
    	/**
    	 * Alias for {@link #scopeName}.
    	 * @see #scopeName
    	 */
    	@AliasFor("scopeName")
    	String value() default "";
    /**
    	 * Specifies the name of the scope to use for the annotated component/bean.
    	 * <p>Defaults to an empty string ({@code ""}) which implies
    	 * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
    	 * @since 4.2
    	 * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
    	 * @see ConfigurableBeanFactory#SCOPE_SINGLETON
    	 * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
    	 * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
    	 * @see #value
    	 */
    	@AliasFor("value")
    	String scopeName() default "";
    
    	ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
    

    用于指定bean对象的生命周期。

    • value:指定作用范围的取值。在注解中默认值是""。但是在spring初始化容器时,会借助ConfigurableBeanFactory接口中的类成员:String SCOPE_SINGLETON = "singleton";

      • singleton:单例模式(默认)

      • prototype:原型模式,每次获取Bean都会创建一个对象

      • request:在web项目中可选,给每一个http request新建一个Bean实例

      • session:在web项目中可选,给每一个http session新建一个Bean实例

      • application:在web项目中可选,bean实例同应用一起创建,并且继续使用到应用结束

        image-20220105164432090

        image-20220105164402952

    • scopeName: 它和value的作用是一样的。

    • proxyMode:它是指定bean对象的代理方式的。指定的是ScopedProxyMode枚举的值

      • DEFAULT:默认值。(就是NO)
      • NO:不使用代理。
      • INTERFACES:使用JDK官方的基于接口的代理。
      • TARGET_CLASS:使用CGLIB基于目标类的子类创建代理对象

    1.16、@PostConstruct

    @Documented
    @Retention (RUNTIME)
    @Target(METHOD)
    public @interface PostConstruct {
    }
    

    用于指定bean对象的初始化方法。

    1.17、@PreDestroy

    @Documented
    @Retention (RUNTIME)
    @Target(METHOD)
    public @interface PreDestroy {
    }
    

    用于指定bean对象的销毁方法。

  • 相关阅读:
    JVM调优-Java中的对象
    Spring MVC如何接收浏览器传递来的请求参数--request--形参--实体类封装
    Navicat for MySQL 64位破解版
    Idea详细配置
    数据库--悲观锁【收藏,待尝试】
    性能问题分析
    java 反射机制之 getDeclaredMethod()获取方法,然后invoke执行实例对应的方法
    Mysql show indexes 查看索引状态
    基于(Redis | Memcache)实现分布式互斥锁
    彻底解决每次打开visio都提示windows正在配置visio的问题
  • 原文地址:https://www.cnblogs.com/myblogstart/p/15767780.html
Copyright © 2011-2022 走看看