Spring之Spring常用组件

@ComponentScan

@ComponentScan(扫描规则)作用:指定要扫描的包
用例:
一、表示扫描此目录下的包

@ComponentScan(value="com.enjoy.cap2")

二、在Cap2MainConfig2加入配置: value: 指定要扫描的包,@Filter: 扫描规则,excludeFilters = Filter[] 指定扫描的时候按照什么规则排除那些组件,includeFilters = Filter[] 指定扫描的时候只需要包含哪些组件,useDefaultFilters = false 默认是true,扫描所有组件,要改成false

@ComponentScan(value="com.enjoy.cap2",includeFilters={    
      @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
      @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class})
},useDefaultFilters=false) //默认是true,扫描所有组件,要改成false,使用自定义扫描范围

//FilterType.ANNOTATION:按照注解
//FilterType.ASSIGNABLE_TYPE:按照给定的类型;比如按BookService类型
//FilterType.ASPECTJ:使用ASPECTJ表达式
//FilterType.REGEX:使用正则指定
//FilterType.CUSTOM:使用自定义规则,自已写类,实现TypeFilter接口

@Import注册bean

 

@Conditional条件注册bean

当IOC容器注册bean, 当操作系统为WINDOWS,注册Lison实例; 当操作系统为LINUX, 注册James实例,此时要用得@Conditional注解进行定制化条件选择注册bean;

@Bean

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

@Configuration

@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

@Service、@Controller、@Repository

将自动扫描路径下面的包,如果一个类带了@Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml文件定义bean了,类似的还包括@Component、@Repository、@Controller。

 

@Primary

当一个接口有2个不同实现时,使用@Autowired注解时会org.springframework.beans.factory.NoUniqueBeanDefinitionException异常信息, @Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常 
详解:

public interface Animal {
    String eat(String food);
}

@Component // 加注解,让spring识别
public class Dog implements Animal {
    @Override
    public String eat(String food) {
        return "狗吃 "+food;
    }
}
public class Cat implements Animal  {
    @Override
    public String eat(String lyrics) {
        return "猫吃"+food;
    }
}
// 只能找到狗
@Component
public class AnimalService {
   @Autowired
   private Animal animal;
   public String eat(){
       return animal.eat("骨头:Σ=3");
   }
}

// 现在优先给猫
// @Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常 
@Primary
@Component
public class Cat implements Animal {
    @Override
    public String eat(String food) {
        return "猫吃"+food;
    }
}

@Lazy

lazy懒加载,只有获取bean是才会加载到IOC容器中

@Configuration
public class LazyMainConfig {
    /**
     * 给容器注册一个bean,类型为返回值类型,默认是单实例
     * 懒加载:主要针对单实例bean,默认在容器启动的时候创建对象
     * 懒加载:容器启动时不创建对象,仅当第一次使用(获取)bean的时候才创建被初始化
     */
    @Lazy
    @Bean
    public Person person () {
        // 在bean对象创建前打印
        System.out.println("给容器中添加person");
        return new Person("fmc",21);
    }
}

 

@Scope

prototype: 多实例:IOC容器启动并不会去调用方法创建对象放在容器中,而是每次获取的时候才会调用方法创建对象
singleton: 单实例(默认):IOC容器启动会调用方法创建对象放到IOC容器中,以后每交获取就是直接从容器(理解成从map.get对象)中拿 
request:
  主要针对WEB应用,同一次请求创建一个实例
session:
  同一个session创建一个实例

@Scope("prototype")
@Bean
public Person person(){
    return new Persion("james",20);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章