1. 程式人生 > >Spring原始碼解析(一)——元件註冊1

Spring原始碼解析(一)——元件註冊1

一、@Configuration&@Bean給容器中註冊元件

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

配置類

import com.atguigu.gmall.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//配置類==配置檔案
@Configuration //告訴spring這是一個配置類
public class MainConfig {

    //給容器註冊一個bean;型別為返回值的型別,id預設是用方法名作為id
    @Bean(value = "person01")
    public Person person() {
        return new Person("lisi", 20);
    }
}

測試類

import com.atguigu.gmall.bean.Person;
import com.atguigu.gmall.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.stream.Stream;

public class MainTest {
    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
        Person person = ac.getBean(Person.class);
        System.out.println(person);

        String[] namesForType = ac.getBeanNamesForType(Person.class);
        Stream.of(namesForType).forEach(string -> System.out.println(string));
    }
}

 

二、@ComponentScan自動掃描元件&指定掃描規則

@Configuration
@ComponentScan(value = "com.ken")
public class MainConfig {
}
public class IocTest {
	@Test
	public void test1() {
		ApplicationContext ac = new AnnotationConfigApplicationContext(MainConfig.class);
		String[] names = ac.getBeanDefinitionNames();
		Stream.of(names).forEach(str -> System.out.println(str));
	}
}

指定掃描規則

excludeFileters

@Configuration
@ComponentScan(value = "com.ken", excludeFilters = {
		@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})})
public class MainConfig {
}

includeFilters表示只包含,注意,要把useDefaultFilters改成false

@Configuration
@ComponentScan(
		value = "com.ken",
		includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})},
		useDefaultFilters = false)
public class MainConfig {
}

ComponentScans

@Configuration
@ComponentScans(
		value = {
				@ComponentScan(
						value = "com.ken",
						includeFilters = {
								@ComponentScan.Filter(type = FilterType.ANNOTATION, 
										classes = {Controller.class})},
						useDefaultFilters = false)
		})
public class MainConfig {
}