Spring常用注解大全

@Configuration

从spring3.0开始出现,相当于配置bean的xml文件,使用该注解可以实现基于java类的配置(其他两种方式可以参考这篇文章:Spring总结(二) 如何配置元数据——将bean注入到Spring容器中)。

源码如下:

被该注解标志的类会创建一个对象,注入到IOC容器中。

简单使用:

package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import entity.Person;

@Configuration
public class Config {
  @Bean
  public Person person() {
    return new Person(18,"dreamcasher");
  }

  public static void main(String[] args) {
    //创建IOC容器,并将实例创建后注入到容器中
    ApplicationContext app = new AnnotationConfigApplicationContext(Config.class);
    Object person = app.getBean("person");
    System.out.println(person);
  }
}

运行结果

@ComponentScan

根据自定义扫描包的路径,将该路径下的被@Component、@Controller、@Service、@Repository注解的类注入到spring容器中。

ps:这里记录一个使用时遇到的坑,注解中有这用一个属性useDefaultFilters,默认值为true,如果值为true,那么在扫描的时候一定会将诸如@Controller、@Service、@Repository注解的类注入到spring容器中,所以一般来说,如果要用到includeFilters属性时,useDefaultFilters应该设置为false。

@Lazy

spring容器在启动的过程中会创建非懒加载的单例,@Lazy注解的类不会在spring容器启动的过程中创建,而是在被get的时候被创建。

@Scope

可以设置该bean是单例(singleton)还是多例(prototype),默认是单例

@Conditional

满足某总条件后,才会将该bean注入到容器中。查看原码如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Conditional {
    Class<? extends Condition>[] value();
}

传入的类对象需要实现Condition接口

@Import

可以将传入的类对象注入到容器中,类型没有限制,比如classes文件下的类,第三方包中的类,或者实现了ImportBEANDefinitionRegistrar接口的类

@Autowired @Qualifier @Resource @Primary 

使用可以参考文章:@Resource与@Autowired 比较

猜你喜欢

转载自blog.csdn.net/qq_28411869/article/details/89314667