@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);
}