• Spring 注解


    @Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。

    @Autowired 注释可以在 setter 方法中被用于自动连接 bean,就像 @Autowired 注释,容器,一个属性或者任意命名的可能带有多个参数的方法。

    Setter 方法中的 @Autowired

    你可以在 XML 文件中的 setter 方法中使用 @Autowired 注释来除去 元素。当 Spring遇到一个在 setter 方法中使用的 @Autowired 注释,它会在方法中视图执行 byType 自动连接。

    (要在bean.xml 写的)

    属性中的 @Autowired

    你可以在属性中使用 @Autowired 注释来除去 setter 方法。当时使用 为自动连接属性传递的时候,Spring 会将这些传递过来的值或者引用自动分配给那些属性  (不用setter方法了)

    构造函数中的 @Autowired

    你也可以在构造函数中使用 @Autowired。一个构造函数 @Autowired 说明当创建 bean 时,即使在 XML 文件中没有使用 元素配置 bean ,构造函数也会被自动连接。  

    Spring @Qualifier 注释

    可能会有这样一种情况,当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。下面显示的是使用 @Qualifier 注释的一个示例。

    基于 Java 的配置

    @Configuration 和 @Bean 注解

    带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。@Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean。最简单可行的 @Configuration 类如下所示:

    package com.tutorialspoint;
    import org.springframework.context.annotation.*;
    @Configuration
    public class HelloWorldConfig {
       @Bean 
       public HelloWorld helloWorld(){
          return new HelloWorld();
       }
    }

    上面的代码将等同于下面的 XML 配置:

    <beans>
       <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" />
    </beans>

    在这里,带有 @Bean 注解的方法名称作为 bean 的 ID,它创建并返回实际的 bean。你的配置类可以声明多个 @Bean。一旦定义了配置类,你就可以使用 AnnotationConfigApplicationContext 来加载并把他们提供给 Spring 容器,如下所示:

    public static void main(String[] args) {
       ApplicationContext ctx = 
       new AnnotationConfigApplicationContext(HelloWorldConfig.class); 
       HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
       helloWorld.setMessage("Hello World!");
       helloWorld.getMessage();
    }


    @Import 注解:

    @import 注解允许从另一个配置类中加载 @Bean 定义。考虑 ConfigA 类,如下所示:

    @Configuration
    public class ConfigA {
       @Bean
       public A a() {
          return new A(); 
       }
    }

    你可以在另一个 Bean 声明中导入上述 Bean 声明,如下所示:

    @Configuration
    @Import(ConfigA.class)
    public class ConfigB {
       @Bean
       public B a() {
          return new A(); 
       }
    }

    现在,当实例化上下文时,不需要同时指定 ConfigA.class 和 ConfigB.class,只有 ConfigB 类需要提供,如下所示:

    public static void main(String[] args) {
       ApplicationContext ctx = 
       new AnnotationConfigApplicationContext(ConfigB.class);
       // now both beans A and B will be available...
       A a = ctx.getBean(A.class);
       B b = ctx.getBean(B.class);
    }
     
  • 相关阅读:
    【转载】stm32的GPIO八种工作模式
    常用数字滤波算法总结
    ST-LINK使用注意
    【转载】深入理解嵌入式开发
    【stm32中断优先级--珍藏版】
    对飞控的理解(一)
    【转载】c语言数据的左移右移
    四轴之第一炸
    linux下查看隐藏文件
    Jetson TK1 五:移植工控机程序到板上
  • 原文地址:https://www.cnblogs.com/zquan/p/10753891.html
Copyright © 2020-2023  润新知