天天看點

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

Spring之Spring常用元件

@Conditional條件注冊bean

當IOC容器注冊bean時, 當作業系統為WINDOWS時,注冊Lison執行個體; 當作業系統為LINUX時, 注冊James執行個體,此時要用得@Conditional注解進行定制化條件選擇注冊bean;

Spring之Spring常用元件

@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

@Configuration
public class LazyMainConfig {
    /**
     * 給容器注冊一個bean,類型為傳回值類型,預設是單執行個體
     * 懶加載:主要針對單執行個體bean,預設在容器啟動的時候建立對象
     * 懶加載:容器啟動時不建立對象,僅當第一次使用(擷取)bean的時候才建立被初始化
     */
    @Lazy
    @Bean
    public Person person () {
        // 在bean對象建立前列印
        System.out.println("給容器中添加person");
        return new Person("fmc",21);
    }
}      

@Scope

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