配置类:congig.java
package com.fsp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Service;
import com.fsp.bean.Person;
//配置类 == 配置文件
@Configuration
/*@ComponentScan(value = "com.fsp",excludeFilters = {
@Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class})
})*/
//excludeFilters = filter[] 指定扫描的时候按照什么规则排除那些组件
@ComponentScan(value = "com.fsp",includeFilters = {
@Filter(type = FilterType.ANNOTATION,classes = {Service.class})
},useDefaultFilters = false)
//includeFilters = filter[] 指定扫描的时候按照什么规则包含哪些组件
//useDefaultFilters默认为true,必须改成false,不还是全部都加载
@ComponentScans(value = {
@ComponentScan(value = "com.fsp",includeFilters = {
@Filter(type = FilterType.ANNOTATION,classes = {Service.class})
},useDefaultFilters = false)
})
//@ComponentScans可以配置多个@ComponentScan
public class MainConfig {
@Bean
public Person person() {
return new Person("fsp",24);
}
}
测试类:IOCTest.java:
package com.fsp.test;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.fsp.config.MainConfig;
public class IOCTest {
@Test
public void test01() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}
}
导入包:
<!-- spirng依赖核心容器 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
源码分析