spring注解

@Required

适用于bean属性setter方法。

此注释仅表示受影响的bean属性必须在配置时填充,通过bean定义中的显式属性值或通过自动装配填充。如果尚未填充受影响的bean属性,容器将引发异常。

@Autowired

注释应用于构造函数。

当 Spring遇到一个在 setter 方法中使用的 @Autowired 注解,它会在方法中执行 byType 自动装配。 

@Qualifier 

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

public class Profile {
   @Autowired
   @Qualifier("student1")
   private Student student;
   public Profile(){
      System.out.println("Inside Profile constructor." );
   }
      ...

 @Configuration 

带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。

@Bean

@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。

添加的bean的id作为方法名,也支持指定任意的初始化和销毁的回调方法。

@Configuration
public class HelloWorldConfig {
   @Bean (initMethod = "init", destroyMethod = "cleanup" )
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

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

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

@import 

它注解允许从另一个配置类中加载 @Bean 定义。

当实例化上下文时,不需要同时指定 ConfigA.class 和 ConfigB.class,只有 ConfigB 类需要提供。

@Import(ConfigA.class)
public class ConfigB {
    ...
}

 @component

把普通pojo实例化到spring容器中,相当于配置文件中的<bean id=" " class=" "/>

泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。

@ComponentScan

该注解默认会扫描该类所在的包下所述的配置类,相当于之前的<context:component-scan>。

两者等效:

@ComponentScan(basePackages = "org.example")
public class AppConfig  {
    ...
}
<context:component-scan base-package="org.example"/>

 

posted @ 2019-08-06 15:34  捺搁pang吱  阅读(133)  评论(0编辑  收藏  举报